How to loop a script?

2 visualizzazioni (ultimi 30 giorni)
sittmo
sittmo il 2 Apr 2022
Risposto: Image Analyst il 2 Apr 2022
Let's say I have a script named "Setup.m" which simply loads in 10 datasets (that are named data_1.csv, data_2.csv, etc) through csvread as follows:
Source_data{4,k} = csvread(sprintf('data_%d.csv',k));
Now, I want to run this script through a for loop using a master script (called "Master.m") as follows:
for k = 1:10;
run Setup
end
But I get the error: "Unrecognized function or variable 'k'."
How can I get the index k to be recognized through the master script?

Risposta accettata

Image Analyst
Image Analyst il 2 Apr 2022
setup.m would look like this:
% Read 10 CSV files into Source_data
Source_data = cell(4, 10);
for k = 1 : 10
baseFileName = sprintf('data_%d.csv',k)
fullFileName = fullfile(pwd, baseFileName);
if isfile(fullFileName)
Source_data{4,k} = csvread(fullFileName);
end
end
Master.m would look like this:
setup;
You would have no access to Source_data in Master.m unless you made setup.m a function and returned it, like this:
% setup.m
% Read 10 CSV files into Source_data
function Source_data = setup()
Source_data = cell(4, 10);
for k = 1 : 10
baseFileName = sprintf('data_%d.csv',k)
fullFileName = fullfile(pwd, baseFileName);
Source_data{4,k} = csvread(fullFileName);
end
and Master.m would look like this:
Source_data = setup;

Più risposte (0)

Categorie

Scopri di più su Introduction to Installation and Licensing in Help Center e File Exchange

Prodotti


Release

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by