MATLAB: If else statement

for loopif statementMATLABtextscan

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

Best Answer

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