필터 지우기
필터 지우기

How to loop a script?

조회 수: 5 (최근 30일)
sittmo
sittmo 2022년 4월 2일
답변: Image Analyst 2022년 4월 2일
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?

채택된 답변

Image Analyst
Image Analyst 2022년 4월 2일
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;

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by