marcman
marcman

Reputation: 3383

Read every other line of data in MATLAB

There are a ton of posts about various ways to read data into MATLAB, but none seem to handle this particular problem. How do I only read every other line without a loop?

I have data formatted like:

1 2 3 4 5 6 7 8 9 string
1 2 -1 5 3 -1 ...
1 2 3 4 5 6 7 8 9 string
1 2 -1 5 3 -1 4 9 -1 ...
...

In other words, the data alternates lines. I can't seem to figure out to only grab the numeric parts of the odd lines.

I know that I can use fscanf as fscanf(fid, '%f %f %f %f %f %f %f %f %f %*s') to actually read the relevant lines. However, this falls apart on the even lines which don't follow the same format.

I also tried fscanf(fid, '%f %f %f %f %f %f %f %f %f %*s\n%*[\n]') thinking this may match 2 lines (due to the included return character), while skipping the data on the even lines due to the asterisk and regex combo. However, this didn't work. It's important to note that the even lines are of different length, so I can't just pattern match them specifically.

How can I do this?

Upvotes: 1

Views: 1282

Answers (1)

BillBokeey
BillBokeey

Reputation: 3476

A working solution : (Although I didn't do any running time test)

I created a text file FileRead with the 4 rows you indicated.

% Open file
fid=fopen('FileRead.txt');

% Read the whole lines of your files in a cell array
A=textscan(fid,'%s','Delimiter','\n');

% Close file
fclose(fid);

% Extract the even lines
Tmp=A{1,1};
out1=Tmp(2:2:end);

% Use cellfun to apply str2num to every cell in out1
out=cellfun(@str2num,out1,'UniformOutput',false);

Output :

enter image description here

Upvotes: 3

Related Questions