How to read every 7:th + i:th (i = 1,2,3..) line into an array

1 view (last 30 days)
Hello good folks! Further below is an example of my data file which is in a matlab code file (.m). I want the data from the 6:th row below each date into an array that looks like this:
if true
M = [13.67 0.02; 13.62 0.03; 13.60 0.02]
end
In other words, where the first row of M has the data of the 7:th line in the file, the second row has the data of the 15:th line of the file, and the third row has data from the 23:rd row of the file, and so on. So basically I want the information of every 7:th + i:th row where i = (1,2,3...).
If you could help me understand how to achieve this, I am eternally greatful.
This is example code of my file:
if true
1999 Oct 30
.......
1.0
13.03 (0.27)
13.87 (0.02)
13.87 (0.01)
13.67 (0.02)
13.65 (0.08)
1999 Oct 31
.......
2.0
13.00 (0.11)
13.80 (0.03)
13.80 (0.02)
13.62 (0.03)
13.58 (0.03)
1999 Nov 01
.......
3.0
13.03 (0.12)
13.80 (0.02)
13.79 (0.02)
13.60 (0.02)
13.56 (0.03)
end
//Oliver
  2 Comments
Oliver Andersen
Oliver Andersen on 23 Apr 2018
Edited: Oliver Andersen on 23 Apr 2018
It is in a matlab code file (.m). I can also copy it into a text file if necessary!

Sign in to comment.

Accepted Answer

KSSV
KSSV on 23 Apr 2018
Copy your data in a text file...
fid = fopen('data.txt','r') ;
S = textscan(fid,'%s','Delimiter','\n');
fclose(fid) ;
S = S{1} ;
S = S(7:8:end) ;
iwant = cell2mat(cellfun(@str2num,S,'un',0))
  2 Comments
Jan
Jan on 23 Apr 2018
Edited: Jan on 23 Apr 2018

Easier and safer:

S     = S(7:8:end);
iwant = str2double(S);

In opposite to str2num the function str2double accepts cell strings directly and does not call eval. But then the parenthesis are a problem.

S     = S(7:8:end);
S     = strrep(strrep(S, '(', ''), ')', '');
iwant = str2double(S);
Oliver Andersen
Oliver Andersen on 24 Apr 2018
Thank you so much both of you! This helped me out tons! Much appreciated

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!