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!