if else statement
1 次查看(过去 30 天)
显示 更早的评论
I have a for loop that used to open text files for plotting, and I want to have an if else statement that will set headerlines equal to 5 for test files having less than 500 rows, and headerlines equal to 400 for those having in excess of 500 rows. I have this so far but it does not seem to be working;
for k = 58:212
inputFileName = sprintf('MT_%05i-000.txt',k);
outputFileName = sprintf('results%05i.tiff',k);
fid = fopen(inputFileName);
newcmd=sprintf('more %s|wc -l', inputFileName);
[p,num_lines]=system(newcmd);
if num_lines<=500
datacell = textscan(fid, '%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','HeaderLines',5);
fclose(fid);
else
datacell = textscan(fid, '%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','HeaderLines',500);
fclose(fid); %number of %f reflects number of columns to record from text file
end
7 个评论
采纳的回答
Thomas
2012-4-11
You could try
for k = 58:212
inputFileName = sprintf('MT_%05i-000.txt',k);
outputFileName = sprintf('results%05i.tiff',k);
fid = fopen(inputFileName);
datacell=textscan(fid,'%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');
if length(datacell)<=500 % this depends on the structure of datacell
actual_data=datacell(5:end) % removing only the 5 headerlines
fclose(fid);
else
actual_data=datacell(401:end) % removing 400 headerlines data > 500 rows
fclose(fid);
end
end
use only the actual_data for computation
EDIT: Try the following
for k = 58:212
inputFileName = sprintf('MT_%05i-000.txt',k);
outputFileName = sprintf('results%05i.tiff',k);
fid = fopen(inputFileName);
c=textscan(fid,'%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','Headerlines',5,'delimiter',' ');
if length(c{1,1})<500 % this tell us there are less than 500 elements
datacell=textscan(fid,'%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','Headerlines',5,'delimiter',' ');
fclose(fid);
else
datacell=textscan(fid,'%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','Headerlines',400,'delimiter',' ');
fclose(fid);
end
end
9 个评论
Thomas
2012-4-11
You are welcome.. Please accept the other answer as well since, it might help someone on a linux system..
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Export 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!