Effacer les filtres
Effacer les filtres

How to loop a script?

5 vues (au cours des 30 derniers jours)
sittmo
sittmo le 2 Avr 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?

Réponse acceptée

Image Analyst
Image Analyst le 2 Avr 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;

Plus de réponses (0)

Catégories

En savoir plus sur MATLAB dans Help Center et File Exchange

Produits


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by