Efficient way to run code multiple times

20 ビュー (過去 30 日間)
Chun Hei Chan
Chun Hei Chan 2023 年 9 月 22 日
回答済み: Star Strider 2023 年 9 月 22 日
Hi,I would like to run the same code many times albeit with many different sets of values for the input . Is there any more efficient alternative to this other than writing a script file and using a for loop? Many thanks
  1 件のコメント
Dyuman Joshi
Dyuman Joshi 2023 年 9 月 22 日
Convert the script to a function and provide inputs via loop.
Depending upon the operation you are doing, you could vectorize your function as well.

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

回答 (1 件)

Star Strider
Star Strider 2023 年 9 月 22 日
I would use the ndgrid function to create matrices from the parameters that you want to vary, convert the output matrices to vectors using reshape, and then run the code once with those vectors.
Example —
a = randn(1,10); % Parameter Vectors
b = randn(1,5);
c = randn(1,7);
[A,B,C] = ndgrid(a,b,c);
Av = A(:); % Reshape MAtrices To Column Vectors
Bv = B(:);
Cv = C(:);
d = @(a,b,c) exp(-(a-1).^2 .* b.*sin(2*pi*c)); % Anonymous Function (For Convenience Only, Can Be A Script)
Dv = d(Av,Bv,Cv);
Results = array2table([Dv Av, Bv, Cv], 'VariableNames',{'D','A','B','C'})
Results = 350×4 table
D A B C _______ _________ _______ ________ 1.2216 -0.67832 -0.5973 -0.51898 1.0263 0.39595 -0.5973 -0.51898 1.1859 -0.54904 -0.5973 -0.51898 1.0651 0.058128 -0.5973 -0.51898 1.077 -0.021925 -0.5973 -0.51898 1.0009 1.112 -0.5973 -0.51898 1.0164 0.52151 -0.5973 -0.51898 1.5411 -1.467 -0.5973 -0.51898 1.1864 -0.55104 -0.5973 -0.51898 1.0458 0.20615 -0.5973 -0.51898 0.88427 -0.67832 0.36703 -0.51898 0.98419 0.39595 0.36703 -0.51898 0.90053 -0.54904 0.36703 -0.51898 0.962 0.058128 0.36703 -0.51898 0.95542 -0.021925 0.36703 -0.51898 0.99945 1.112 0.36703 -0.51898
All combinations of the parameters were presented at once in this example, avoiding nested loops.
Creating the anonymous function (or a function from your script), allows a bit more flexibility in the simulation, because the variable names do not need to be completely re-written in the function if you change them.
.

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by