For loop error: unable to perform assignment because left and right sides have a different number of elements
Show older comments
I am struggling to create a forloop which reduces the following task into a few lines of code:
resp1 = squeeze(resp(:,1,:));
resp2 = squeeze(resp(:,2,:));
resp3 = squeeze(resp(:,3,:));
resp4 = squeeze(resp(:,4,:));
resp5 = squeeze(resp(:,5,:));
resp6 = squeeze(resp(:,6,:));
resp7 = squeeze(resp(:,7,:));
imp_level(iter_rep-num_draw_discard,:,:) = resp1;
imp_slope(iter_rep-num_draw_discard,:,:) = resp2;
imp_curv(iter_rep-num_draw_discard,:,:) = resp3;
imp_unrate(iter_rep-num_draw_discard,:,:) = resp4;
imp_pce_ch(iter_rep-num_draw_discard,:,:) = resp5;
imp_tcu_ch(iter_rep-num_draw_discard,:,:) = resp6;
imp_effr(iter_rep-num_draw_discard,:,:) = resp7;
I've tried the following but got an error
variables = {'level', 'slope', 'curv', 'unrate', 'pce_ch','tcu_ch', 'effr' };
range = linspace(1,size(variables,2),7);
% betas_exog is a (324 x 7) dimension matrix
for i = 1:size(betas_exog, 2)
resp_range(i) = squeeze(resp(:,i,:));
imp_variables{i}(iter_rep-num_draw_discard,:,:) = resp(i)
end
I would appreciate your help in fixing the error and creating a workable for loop.
6 Comments
Cris LaPierre
on 26 Dec 2020
What error message did you get? Please copy/paste the entire message (all the red text) here.
matlabuser
on 26 Dec 2020
James Tursa
on 27 Dec 2020
The general procedure for debugging this type of error is to type the following at the MATLAB command prompt:
dbstop if error
then run your code. When the error occurs, the code will pause with all variables intact. Examine all of the variables and expressions on the line that is generating the error to see what is causing the problem. Then backtrack in your code to figure out why the sizes are not what you expected.
This won't work, it will not generate variable names like "imp_level" as your example shows:
variables = {'level', 'slope', 'curv', 'unrate', 'pce_ch','tcu_ch', 'effr' };
..
imp_variables{i}..
In any case, that approach is entirely wrong, unless you want to force yourself into writing slow, complex, inefficient, obfuscated code which is buggy and difficult to debug:
Instead of trying to access variable names dynamically, the much more efficient approach would be to use structure fields or a table. Or perhaps best of all: just leave the data and meta-data unchanged and access them using indexing. Or if you have a fixed, small number of such allocations, just write them out explicitly.
J. Alex Lee
on 28 Dec 2020
Are you just trying to re-order the dimensions? Or would doing that first let you index more easily for whatever you are trying to do?
matlabuser
on 30 Dec 2020
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!