How do I use use sprtintf for a loop?

조회 수: 10 (최근 30일)
rafe brooks
rafe brooks 2020년 12월 6일
댓글: dpb 2020년 12월 6일
I am needing to import a number of files from a folder using a loop so I dont have to re-write the code. The files are named 'Monday11' to 'Monday50' so created a loop using i=11:50. I then need a specific column to be read into matlab from each excel file from F5:F6005. My code so far is:
for i=11:50
gA=sprintf('Monday%d.csv',i);
gA(i)=readmatrix(gA);
end
How can I do this?
thanks in advance!

답변 (1개)

dpb
dpb 2020년 12월 6일
Probably the most-asked question of all...don't build the names, use dir
d=dir('Monday*.csv'); % better to use fully-qualified name search, but if files in local folder ok
for i=1:numel(d)
data=readmatrix(d(i).name,'Range','F');
% do whatever with the dataset here before going on to next...
end
  댓글 수: 2
rafe brooks
rafe brooks 2020년 12월 6일
When i put this into my script it doesnt come up as a variable 'data', It doesnt say theres any errors but doesnt come out with any matrix. my script now reads:
addpath('input data','Group A');
close all; clear all; clc;
z_force=NaN(6000,50); %creating matrix for the Z plane reaction force
s_rate=1000; % the sample rate of the force plate
g=-9.81; %acceleration due to gravity
%% reading the data from the files
d=dir('Monday*.csv');
for i=1:numel(d)
data=readmatrix(d(i).name,'Range','F6:F6005');
end
dpb
dpb 2020년 12월 6일
So, what does
whos d
return after the call to dir()?
Sure you got the right folder so it isn't empty, first?
After that, then it's whether the data file is what is advertised to be.
NB: The way you wrote the loop above, all you will have will be the last file found; all the rest will have been overwritten the subsequent time thru the loop since nothing was done with those results first.

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by