Retrieve loop counter values in nested loop, and plotting specific calculation
4 views (last 30 days)
Show older comments
Hello all. My questions are as commentated
count = 0 ;
vec = zeros([],7) ;
for a=1:3
A= 2*a ;
for b=a+1:6
B=3*b ;
for c=b+1:10
C=4*c ;
count = count+1 ;
total=sum([A B C])
vec(count,:)=[a b c A B C total];
end
end
end
value = max(total) % get max and return values of a,b,c when this happens
% plotting corresponding individual calculation A B C for the max(total)
end
4 Comments
Adam Danz
on 15 Aug 2018
I don't follow your explanation. However, when I run your code I get an error on the first iteration since
[a b c A B C total]
has 10 elements but
vec(count,:)
expects 11 elements. On the 2nd iteration there are 11 elements in [a b c...] so there isn't an error.
Accepted Answer
dpb
on 15 Aug 2018
Edited: dpb
on 15 Aug 2018
I didn't notice the "growing" of the vector length...you've got to use a cell array to handle that.
total=[]; vec=[];
count=0;
for a=1:3
A= 2*a ;
for b=a+1:6
B=3*(1:b);
for c=b+1:10
C=4*(1:c);
count=count+1 ;
total(count)=sum([A B C]);
vec{count,1}=[sum([A B C]) a b c A B C]; % make column cell array
end
end
end
[value,ival]=max(total);
To retrieve the content use
vec{ival}
NB: that with the given positive value the maximum is always the last value so there's no need to search; one presumes this is artificial example.
One could also do the max() on the running total in the loop; there's no real reason to save anything except the maximum and conditions so far to get the actual result
8 Comments
dpb
on 15 Aug 2018
OK...if wish, post a new Q? that illustrates your final output storage arrangement and what you want to retrieve and we can address the efficiencies regarding what, specifically, to actually store and how to retrieve what's needed for the real application.
I just introduced the total vector as an intermediary device to get to an answer while still trying to define the problem.
If it's so that you do want/need the subvectors then I recommend the probably solution is to save 2D cell array instead of 1D array of variable-length vector that combines the different pieces.
More Answers (0)
See Also
Categories
Find more on Exponents and Logarithms 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!