Borrar filtros
Borrar filtros

How to loop a script?

5 visualizaciones (últimos 30 días)
sittmo
sittmo el 2 de Abr. de 2022
Respondida: Image Analyst el 2 de Abr. de 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?

Respuesta aceptada

Image Analyst
Image Analyst el 2 de Abr. de 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;

Más respuestas (0)

Categorías

Más información sobre MATLAB en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by