Efficient way to run code multiple times
14 次查看(过去 30 天)
显示 更早的评论
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
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
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'})
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.
.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!