[大至急お願い致します] for文の入れ子に関しまして
Show older comments
以下のような関数funに対し,4変数をそれぞれ1~10まで変化させて代入し計10000個の結果を見たいのですが,
matlabではfor文を入れ子にすると処理速度が落ちると聞きました.for文を使わないで10000個の結果を出力する
方法はありませんでしょうか.
よろしくお願い致します.
syms a b c d
fun(a,b,c,d) = (a + b)^c * d
for i=1:10
for j=1:10
for k=1:10
for l=1:10
fun(i,j,k,l);
end
end
end
end
Accepted Answer
More Answers (1)
madhan ravi
on 10 Oct 2020
[d, c, b, a] = ndgrid(1:10);
fun = @(a,b,c,d) (a + b).^c .* d;
fun(a(:), b(:), c(:), d(:))
7 Comments
maro_ta
on 10 Oct 2020
Shota Kato
on 10 Oct 2020
想定している順番と異なるかもしれませんが,10000個の計算結果は得られませんか?
madhan ravi
on 10 Oct 2020
Why?
Shota Kato
on 10 Oct 2020
@ madhan ravi
I mean your answer is correct.
However, it is not clear which arguments are used in the output...
maro_ta
on 10 Oct 2020
Shota Kato
on 10 Oct 2020
上記にコマンドをそのままコマンドラインで実行すると,小数の結果が見えます.
というのも,一番上に1.0e+14がついているからです.
桁数の異なる数を一度に出力しているので,小数であるかのように見える,ということだと思います.

madhan ravi
on 10 Oct 2020
Edited: madhan ravi
on 10 Oct 2020
format longg
[d, c, b, a] = ndgrid(1 : 10);
fun = @(a, b, c, d) (a + b).^c .* d;
Wanted1 = fun(a(:), b(:), c(:), d(:));
Wanted2 = zeros(1e4, 1);
k1 = 1;
for ii = 1 : 10
for jj = 1 : 10
for k = 1 : 10
for l = 1 : 10
Wanted2(k1) = fun(ii, jj, k, l);
k1 = k1 + 1;
end
end
end
end
isequal(Wanted1, Wanted2) % check if they are equal
Categories
Find more on Deep Learning Toolbox 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!