简体   繁体   中英

How to run a function inside a for loop 10000 times and record 3 separate outputs

I'm working in MATLAB and I'm still very new to it.

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 save each output from each of the 10,000 trials so that I can then pull the average from each. However my code just keeps producing one output for each.

`for trials = 1:10000
[S,M,L] = crayonBreak(); % function to run
Sl = [S; trials]; % list for all S values
Ml = [M; trials]; % list for all M values
Ll = [L; trials]; % list for all L values
end`
`

Here is the for loop I have currently. I don't think I'm recording the values in a list correctly but I don't know what I'm doing wrong.

First, let's make a dummy function so that we can test properly

crayonBreak = @()deal(rand,rand,rand);  %This is just a function that will generate three outputs.

The original code overwrites the Sl values at each loop, so the final value is the last result of crayonBreal , plus the number 10000.

for trials = 1:10000
    [S,M,L] = crayonBreak(); % function to run
    Sl = [S; trials]; % list for all S values
    Ml = [M; trials]; % list for all M values
    Ll = [L; trials]; % list for all L values
end

%>> Sl
%Sl =
%         0.477917969692359
%                     10000    

The smallest adjustment to this code is to concatenate the most recent result wth the previous results during each pass through the loop. That would look like this.

Sl=[];  %Iniitalize the outputs to an emmpty array
Ml=[];
Ll=[];
for trials = 1:10000
    [S,M,L] = crayonBreak(); % function to run
    Sl = [Sl; S]; % At leash loop, concatenate the new value to the growing array
    Ml = [Ml; M]; % 
    Ll = [Ll; L]; % 
end

%>> Sl
%ans =
%         0.920537104151778
%          0.83184440865223
%         0.567461009088077
%         ...

A better implementation is to pre-allocate the outputs first, and then insert the results as you go. That would look like this:

nTrials = 10000;
Sl=nan(nTrials,1);  %Iniitalize the outputs to a properly sized array of NaNs
Ml=nan(nTrials,1);
Ll=nan(nTrials,1);
for trials = 1:10000
    [S,M,L] = crayonBreak(); % function to run
    Sl(trials) = S; % At leash loop, insert the value into the output
    Ml(trials) = M; % 
    Ll(trials) = L; % 
end

%>> Sl(1:5)
%ans =
%         0.779202300519089
%         0.510303051476698
%         0.415940683606639
%         ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM