[大至急お願い致します] 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

 Accepted Answer

Shota Kato
Shota Kato on 10 Oct 2020

0 votes

Neural Network Toolboxがあるならcomvbec関数,そうでなければMATLAB Centralにあるallcomb関数を用いることで,複数組のベクトルの値からすべての組み合わせを取得することができます.
(参考:https://jp.mathworks.com/matlabcentral/answers/338295-matlab)
これを用いると,10,000個の計算結果をfor文を用いることなく算出できます.
% Neural Network Toolboxがある場合
X = (combvec(1:10, 1:10, 1:10, 1:10))'
% Neural Network Toolboxがある場合
% X = allcomb(1:10, 1:10, 1:10, 1:10);
A = X(:, 1);
B = X(:, 2);
C = X(:, 3);
D = X(:, 4);
ANS = (A + B) .^ C .* D;

5 Comments

maro_ta
maro_ta on 10 Oct 2020
ご返信ありがとうございます.
アドオンの追加にNeural Network Toolboxがないのですが,combvec関数はDeep Learning Toolboxでも使用可能でしょうか?
maro_ta
maro_ta on 10 Oct 2020
Deep Learning Toolboxをインストールいたしましたが,使用可能でした.
すべての組み合わせを並列処理できる関数が欲しかったのですが,まさにそのものでした.
ありがとうございました!
maro_ta
maro_ta on 10 Oct 2020
たびたび申し訳ありません.
10000通りの出力を得られたのですが,@madhan raviさんのものと同様にすべて1未満の少数の出力となってしまいました.
出力形式の問題なのでしょうか?
Shota Kato
Shota Kato on 10 Oct 2020
私の環境では,ANSとして,このような出力が得られました.
出力形式の問題かもしれません.
ワークスペースの変数をダブルクリックすると,変数の詳細を見ることができますが,出力結果はどのように確認していますか?
maro_ta
maro_ta on 10 Oct 2020
自分はコマンドウィンドウで結果を見ていたのですが,特にe+14の表記がありませんでしたので少数であるかのように見えていました .
ワークスペースで確認したところ,きちんと出力されておりました.何度もありがとうございました!

Sign in to comment.

More Answers (1)

madhan ravi
madhan ravi on 10 Oct 2020

1 vote

[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
maro_ta on 10 Oct 2020
thank you for answering but output is incorrect ...
Shota Kato
Shota Kato on 10 Oct 2020
想定している順番と異なるかもしれませんが,10000個の計算結果は得られませんか?
madhan ravi
madhan ravi on 10 Oct 2020
Why?
Shota Kato
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
maro_ta on 10 Oct 2020
ご返信ありがとうございます.
10000個の結果は得られますが,fun(a(:), b(:), c(:), d(:))がすべて1未満の少数の出力となっていました.
Shota Kato
Shota Kato on 10 Oct 2020
上記にコマンドをそのままコマンドラインで実行すると,小数の結果が見えます.
というのも,一番上に1.0e+14がついているからです.
桁数の異なる数を一度に出力しているので,小数であるかのように見える,ということだと思います.
madhan ravi
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

Sign in to comment.

Categories

Find more on Deep Learning Toolbox in Help Center and File Exchange

Asked:

on 10 Oct 2020

Commented:

on 10 Oct 2020

Community Treasure Hunt

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

Start Hunting!