Retrieve loop counter values in nested loop, and plotting specific calculation
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
Adam Danz
2018-8-15
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.
采纳的回答
dpb
2018-8-15
编辑:dpb
2018-8-15
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 个评论
dpb
2018-8-15
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Exponents and Logarithms 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!