Run a function inside a for loop 10,000 times and record the 3 separate outputs for each trial

2 views (last 30 days)
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
VBBV on 28 Nov 2022
Sl(trials) = S;
Ml(trials) = M;
Ll(trials) = L;
  3 Comments
VBBV
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,
Sl = 1×10000
0.6659 0.6360 0.1235 0.2869 0.8678 0.8752 0.2682 0.3422 0.1486 0.7197 0.4954 0.7328 0.3132 0.1744 0.7686 0.2773 0.2526 0.6079 0.7764 0.9991 0.8646 0.9189 0.0676 0.4408 0.2586 0.1732 0.3026 0.3628 0.3977 0.1412
Ml = 1×10000
0.6169 0.9453 0.6292 0.7253 0.2442 0.9436 0.7622 0.3416 0.7905 0.5936 0.7303 0.8699 0.3346 0.3015 0.8931 0.6656 0.1587 0.0749 0.9722 0.6737 0.6742 0.2671 0.5881 0.4916 0.3278 0.3150 0.0546 0.2817 0.9364 0.3957
Ll = 1×10000
0.9494 0.9364 0.2546 0.4788 0.3378 0.0563 0.8846 0.2533 0.4457 0.5506 0.6268 0.2566 0.4805 0.3051 0.2895 0.0662 0.4002 0.2488 0.2092 0.6633 0.6558 0.5478 0.6782 0.9287 0.8313 0.2034 0.0531 0.5057 0.3346 0.1618
mean(Sl)
ans = 0.5024
mean(Ml)
ans = 0.5034
mean(Ll)
ans = 0.5003
function [S,M,L] = crayonBreak()
S = rand(1);
M = rand(1);
L = rand(1);
end

Sign in to comment.


Stephen23
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)
S = 1×10000
0.7019 0.0534 0.8125 0.5301 0.4659 0.2806 0.3872 0.4478 0.5410 0.4365 0.1543 0.6310 0.8740 0.9585 0.0317 0.5657 0.8402 0.4991 0.9272 0.1651 0.6194 0.1985 0.2538 0.7495 0.7372 0.7060 0.3727 0.0894 0.7250 0.6181
mean(S)
ans = 0.4969
function [S,M,L] = crayonBreak()
S = rand(1);
M = rand(1);
L = rand(1);
end

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by