Reading/Extracting data from a text file in a certain format using Matlab
7 views (last 30 days)
I am a beginner in Matlab. I need to extract some required data [ I index, J index of cells and their lengths(DX) and widths(DY)] from the attached text file in the following formate:
I J DX DY
2 2 35.53 51.93
3 2 35.53 51.93
4 2 35.53 51.93
5 2 35.53 51.93
196 199 35.53 51.93
197 199 35.53 51.93
Turlough Hughes on 4 Oct 2019
If i'm correct in my understanding of your data, it looks like you want to take the first and fifth line of data for every 5 lines in your text file.
You could try reading the text file line by line using fgetl(). This returns the next line of your file as a character vector, then use str2num() to convert your character vector to a 1x2 array in this case. I've added in conditions to store only the lines you specified. Note that you need to have waterscape2.txt in your current working directory or else filename has to be changed, for example filename='C:\...\waterscape2.txt'.
fid = fopen(filename);
fgetl(fid); %read first line of text file
tline=fgetl(fid); %read second line
c=0; ij=; DxDy=;
if mod(c+4,5)==0 % store when c=1,6,11,...,etc.
if mod(c,5)==0 % store when c=5,10,15,...,etc.
tline = fgetl(fid);
More Answers (1)
Turlough Hughes on 8 Oct 2019
Edited: Turlough Hughes on 8 Oct 2019
On your first question; The last index of an array can be specified by calling the index end. end + 1 means we add an additional row at the end of the arrays ij and DxDy to save the new lines read from your file. It might be helpful for you to look up matrix indexing in the documentation or the following video.
For the second question, one way is to do the following:
DMDN = ones(size(ij));
data = [data DMDN];