Run a script file multiple times and save variable values to array

I have a script file that I would like to run 50 times. Each time the script file is executed I would like certain variables generated by the script file to be saved in an array I have created in the driver file. I have tried creating a driver file with a for loop and using the control variable for the for loop to index the array entries, but Matlab seems to not let me access the control variable (or any other variables in the driver file). Is there an easy way to do this? I am familiar with diary but the text output is tedious to manually convert to an array.

Answers (1)

What is a "driver file"? "Matlab seems to not let me access the control variable" - what does this mean? What do you observe? Which code do you try?
It is easy actually:
% YourScript.m
% Your script (prefer functions for a clean programming style!)
a = rand
and the main function for the loop:
function yourLoop
result = zeros(1, 50);
for k = 1:50
run('YourScript')
result(k) = a;
end
end

5 Comments

I was trying to do something like this:
trials = 50;
Times = zeros(trials,3);
for k=1:trials
ResNet_C2F
Times(k,1) = time1
Times(k,2) = time2
Times(k,3) = time3
but it would throw an error on the Times(k,1) = time1 line because it said there was no variable k. I didn't realize you had to add the word run, thank you you for your help!!
Actually, for whatever reason this is still not working. I tried
function [Times,Results,Validation] = ResNet_C2F_Driver1(trials)
Times = zeros(trials,3);
Results = zeros(trials,6);
Validation = zeros(trials,3);
for k=1:trials
run('ResNet_C2F')
Times(k,1) = time1;
Times(k,2) = time2;
...etc
and got the error "Reference to a cleared variable k.". Do you know why this is?
Get rid of all "clear" statements you have in your code.
Wow can't believe I didn't catch that. Thanks for helping an undergraduate out
@Evan: clear is rarely useful in Matlab, but it causes troubles frequently.

Sign in to comment.

Categories

Find more on Scope Variables and Generate Names in Help Center and File Exchange

Tags

Asked:

on 27 Feb 2019

Commented:

Jan
on 28 Feb 2019

Community Treasure Hunt

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

Start Hunting!