MATLAB Answers

How can I call a script within a for loop, looping over multiple files?

조회 수: 3(최근 30일)
Caitlin Ridgewell
Caitlin Ridgewell 2021년 7월 21일
댓글: Caitlin Ridgewell 2021년 7월 22일
Hi all, I know this information must be out there somewhere but I'm just not seeing what I need or maybe I'm just not understanding what I'm reading since I'm not very MATLAB literate. Anyway, thank you for your help in advance.
I'm trying to put together a script containing a for loop, in which I can call another script and apply that second script to a number of files. The files are organized by participant ID and by visit number so in my loop script (loop.m), I have included variable identifiers:
ID = {'1','2','3'};
Visit = {'1','2'};
These IDs correspond to the IDs referenced in the script that I'm calling and have the same name as in the script that I'm calling. Once I've specified those variables, I start my for loop:
for nSubject = 1:length(ID)
for nVisit = 1:length(Visit)
result = scriptname(nSubject,nVisit));
Within the second script, here referred to as scriptname.m, the first few lines take that information and then start working with it:
function task1 = scriptname(ID,Visit)
filename = append('ECG_',ID,'_',Visit,'.txt');
filelocation = fullfile('path\',ID,'\',Visit);
What I'm running into is that when I run loop.m, I get errors.
Error using append (line 62)
Input must be a string array, character vector, or cell array of character vectors.
Error in scriptname (line 8)
filename = append('ECG_',ID,'_',Visit,'.txt');
Error in loop (line 22)
result = scriptname(nSubject,nVisit);
I think I have a few problems:
  1. It looks like ID and possibly also Visit aren't creating correctly - when I run that part of the script, the resulting cells includes all the participant IDs in the origin file, even if I haven't specified those IDs.
  2. I'm probably calling the script incorrectly in the for loop. I know that scriptname.m works just fine when I specify ID and Visit alone and then just run scriptname.m - so it sounds to me like loop.m is the problem, not necessarily scriptname.m.
Any suggestions for me? THANK YOU
  댓글 수: 5
Caitlin Ridgewell
Caitlin Ridgewell 2021년 7월 22일
Excellent point, Matt. I'll look into how to improve my script so it's written appropriately and doesn't have this problem anymore. Thanks for pointing that out!

댓글을 달려면 로그인하십시오.

채택된 답변

Matt J
Matt J 2021년 7월 21일
result = scriptname(ID{nSubject},Visit{nVisit});

추가 답변(0개)




Community Treasure Hunt

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

Start Hunting!

Translated by