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!