Run a function inside a for loop 10,000 times and record the 3 separate outputs for each trial
2 views (last 30 days)
Show older comments
I'm very new to MATLAB and I'm trying to import a function and run it 10,000 times inside a for loop.
The function produces 3 separate outputs and I need to record each output from each trial in an array so that I can then pull the mean value from each array. However I cannot get it to work. Here is for loop I have currently.
Please help.
for trials = 1:10000
[S,M,L] = crayonBreak();
Sl = [Sl; S];
Ml = [Ml; M];
Ll = [Ll; L];
end
Answers (2)
VBBV
on 28 Nov 2022
Sl(trials) = S;
Ml(trials) = M;
Ll(trials) = L;
3 Comments
VBBV
on 28 Nov 2022
I need to record each output from each trial in an array so that I can then pull the mean value from each array
As mentioned in your question, mean will give only value for any length of array. Do you look at Sl, Ml, Ll arrays below ? they are 1 x 10000 it implies all 10000 values are stored in those arrays as shown below
for trials = 1:10000
[S,M,L] = crayonBreak();
Sl(trials) = S;
Ml(trials) = M;
Ll(trials) = L;
end
Sl, Ml, Ll,
mean(Sl)
mean(Ml)
mean(Ll)
function [S,M,L] = crayonBreak()
S = rand(1);
M = rand(1);
L = rand(1);
end
Stephen23
on 29 Nov 2022
Edited: Stephen23
on 29 Nov 2022
Assuming that each output is a scalar double:
N = 1e4;
S = nan(1,N);
M = nan(1,N);
L = nan(1,N);
for k = 1:N
[S(k),M(k),L(k)] = crayonBreak();
end
Now lets calculate the mean of one of those vectors:
display(S)
mean(S)
function [S,M,L] = crayonBreak()
S = rand(1);
M = rand(1);
L = rand(1);
end
0 Comments
See Also
Categories
Find more on Logical 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!