MATLAB: How do i change the script to print out the second word of each even line

input

fn = input( 'file name: ', 's' );
fh = fopen( fn, 'r' );
ln = '';
count=1;
while ischar( ln )
ln = fgets( fh );
if (ischar( ln ) && mod(count,2)==0)
fprintf( ln );
end
count=count+1;
end
fclose( fh );
I created a script that prints out the even line of a input file but i dont know how to make it print out the second word of each even line.

Best Answer

Instead of reading the file line by line you could read in the entire text file and then extract the 2nd word from even numbered lines of the text with just 3 lines of code.
% Read entire file as a char array
C = fileread('MyTextFile.txt');
% Split the char array by line and then split by word.
% ca{j}{m} is the m_th word in the j_th line of text.
ca = cellfun(@strsplit,strtrim(strsplit(C, newline())),'UniformOutput',false);
% get 2nd word of each even numbered line unless the line only has 1 word.
% If the line is empty, it will return an empty.
words = cellfun(@(s)s{min(numel(s),2)},ca(2:2:end),'UniformOutput',false);
% [1]^ [2]^^^^^^^^
% [1] get 2nd word
% [2] isolate even-numbered lines
If you'd rather maintain your fgets method, add the two lines below to display the 2nd word of ln unless it only has 1 word in which case it displays the first word.
lnSplit = strsplit(ln);
fprintf('%s\n',lnSplit{min(numel(lnSplit),2)})
% ^^ Assuming you want a line break