[大至急お願い致します] for文の入れ子に関しまして
显示 更早的评论
以下のような関数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
采纳的回答
更多回答(1 个)
madhan ravi
2020-10-10
[d, c, b, a] = ndgrid(1:10);
fun = @(a,b,c,d) (a + b).^c .* d;
fun(a(:), b(:), c(:), d(:))
7 个评论
maro_ta
2020-10-10
Shota Kato
2020-10-10
想定している順番と異なるかもしれませんが,10000個の計算結果は得られませんか?
madhan ravi
2020-10-10
Why?
Shota Kato
2020-10-10
@ madhan ravi
I mean your answer is correct.
However, it is not clear which arguments are used in the output...
maro_ta
2020-10-10
Shota Kato
2020-10-10
上記にコマンドをそのままコマンドラインで実行すると,小数の結果が見えます.
というのも,一番上に1.0e+14がついているからです.
桁数の異なる数を一度に出力しているので,小数であるかのように見える,ということだと思います.

madhan ravi
2020-10-10
编辑:madhan ravi
2020-10-10
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
类别
在 帮助中心 和 File Exchange 中查找有关 Deep Learning Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!