how to populate a cell with a loop

2 次查看(过去 30 天)
This is what I have with my code so far.
a = dir;
i=3;
d = a(i).name;
A = zeros(40,55);
while i<=43
A = textscan(fopen(d),'%f %f %f %f %f %f %f %f %f %f %f %f %f %f %s %s %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %s %s %f %f %f %f %f %f %f %f', 'Delimiter',',','Headerlines',1);
A_time = A{1,1};
B_time = num2str(A_time);
x = datenum(B_time,'yyyymmddHHMM');
i=i+1;
end
I have 43 data files in my folder. when I run this, A becomes a 1x55 cell with data from the first file. I'd like to make it so that the A on the outside of the loop is populated with the cell data from each file folder. Please help

采纳的回答

dpb
dpb 2018-10-6
编辑:dpb 2018-10-7
fmt=[repmat('%f',1,14) repmat('%s',1,2) repmat('%f',1,29) repmat('%s',1,2) repmat('%f',1,8)]; % legible (sorta') format string
d=dir('AppropriateString*.ext'); % setup dir() to return the wanted actual files
for i=1:length(d) % iterate over files found
fid=fopen(d(i).name),'r');
A(i)=textscan(fid,fmt,'Delimiter',',','Headerlines',1);
fid=fclose(fid);
end
Will leave with cell array of one row per file.
Which specific columns are date/time data? The two sets of '%s' I presume?
datenum has been deprecated; better to use datetime instead and easier than textscan would be to use readtable.
Let us know the actual date format/location in the files and we can write specific conversion for it, too...
ADDENDUM
OK, if the string fields are really just 'nan' or variant thereof, use numeric format for them and convert them on input as well.
...
fmt=['%{yyyyMMddHHmmss}D' repmat('%f',1,54)]; % legible format string
for i=1:length(d) % iterate over files found
fid=fopen(d(i).name),'r');
A{i}=textscan(fid,fmt,'Delimiter',',','Headerlines',1,'collectoutput',1);
fid=fclose(fid);
end
using datetime class rather than the deprecated datenum for the date field.
You might also consider readtable depending on what your next step(s) are with these data.
  4 个评论
Susan Santiago
Susan Santiago 2018-10-7
that's just columns of NAN. The date is written as a number which is why in the code I posted, I convert it to a string and then get the serial date number
dpb
dpb 2018-10-7
编辑:dpb 2018-10-7
'NaN' will be read as NaN, don't need a string format for it; that's what made think those probably were/could be date/time fields, maybe.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by