How can I save the results of a nested loop?
4 views (last 30 days)
Show older comments
Shahpour Turkian
on 9 Sep 2022
Commented: Shahpour Turkian
on 9 Sep 2022
I have two input matrices: qq and om
l = [0 0.05 0.1 0.15];
qq = perms(l).';
m = [0.01 0.001 0.0001 0.0002];
om = perms(m);
These inputs get fed in my Function which in return will output a 1-by4 output, so I created a 24-by-4 results
results = zeros(width(om), length(om)*length(qq));
for i=1:length(om)
for j=1:length(qq)
results(i,j) = Function(qq(:,j),om(i,:))
end
end
since the output of my function is 1-by-4, I can't save it in a 1-by-1 cell so I get:
I get: Unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side is 1-by-4.
I also tried
[results(i,1) results(i,2) results(i,3) results(i,4)] = AA_BL_M(qq(:,j),om(i,:))
this seems to work but doesn't save the iterations:
results = AA_BL_M(qq(:,j),om(i,:))
0 Comments
Accepted Answer
Cris LaPierre
on 9 Sep 2022
Note that your preallocation of results does not match the number of times your for loops will run. Keeping your for loops the way they are, your resutls variable will need to be of size (i,j,4) to capture your results (or a (i,j) cell array)
You could try this
results = zeros(length(om), length(qq),4);
...
results(i,j,:) = Function(qq(:,j),om(i,:))
or
results = cell(length(om), length(qq));
...
results{i,j} = Function(qq(:,j),om(i,:))
More Answers (0)
See Also
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!