Storing the results from nested loop

Hello, I have reviewed other posts and videos on this but those solutions did not work - well, not elegantly. How do I store each iteration of the following nested loop?
for a=0:3
A= 2*a
for b=a+1:6
B=3*b
for c=b+1:10
C=4*c
vec=[A B C] % to store output of each iteration
end
plot(vec,'r--') % plot each iteration in its entirety, each time
end
end

 採用された回答

KSSV
KSSV 2018 年 6 月 27 日

0 投票

count = 0 ;
vec = zeros([],3) ;
for a=0:3
A= 2*a ;
for b=a+1:6
B=3*b ;
for c=b+1:10
count = count+1 ;
C=4*c ;
vec(count,:)=[A B C] ; % to store output of each iteration
end
plot(vec(count,:),'r--') % plot each iteration in its entirety, each time
end
end

2 件のコメント

Guillaume
Guillaume 2018 年 6 月 27 日
I think this needs a
figure;
hold on;
before the first loop to avoid overwriting each plot at each iteration.
Pit Probst
Pit Probst 2018 年 8 月 11 日
編集済み: Pit Probst 2018 年 8 月 11 日
thanks both!
KSSV, to retrieve the values of a,b,c for which the sum maximum. And plot the calcuated A,B,C up to these values on a,b,c. How could I do that?
%
count = 0 ;
vec = zeros([],3) ;
for a=0:3
A= 2*a ;
for b=a+1:6
B=3*b ;
for c=b+1:10
C=4*c ;
count = count+1 ;
vec(count,:)=sum([A B C]) ;
end
max(vec) % what were the values of a, b,c for this
% plot
end
end

サインインしてコメントする。

その他の回答 (1 件)

Guillaume
Guillaume 2018 年 6 月 27 日
編集済み: Guillaume 2018 年 6 月 27 日

1 投票

You could of course not bother with the loops at all:
a = 0:3;
b = a(1)+1:6; %too many elements, the extra will be removed later
c = b(1)+1:10; %too many elements, the extra will be removed later
[A, B, C] = ndgrid(a, b, c);
abc = [A(:), B(:), C(:)];
%now remove unwanted entries
abc(abc(:, 2) <= abc(:, 1) | abc(:, 3) <= abc(:, 2), :) = [];
%calculate vec and plot all
vec = abc .* [2 3 4];
plot([1 2 3], vec, 'r--');

2 件のコメント

Pit Probst
Pit Probst 2018 年 8 月 11 日
Im coding an optimization. compared with KSSV and my own code, yours gives a slightly different answer - might be the actual right answer too but ill check on it. thanks for the vectorized format!
Guillaume
Guillaume 2018 年 8 月 12 日
The orders of the rows is different, but I'm assuming it does not matter. If it does, at the end:
vec = sortrows(vec);

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeStartup and Shutdown についてさらに検索

製品

リリース

R2018a

タグ

質問済み:

2018 年 6 月 27 日

コメント済み:

2018 年 8 月 12 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by