how to read columns with different length correctly in txt file?

9 views (last 30 days)
I have a simple array saved in test.txt file:
[1 2 3;
4 5 6;
2 ]
I used importdata:
>> x=importdata('test.txt')
x =
1 2 3
4 5 6
2 NaN NaN
I also tried dlmread:
>> x=dlmread('test.txt')
x =
1 2 3
4 5 6
2 0 0
>>
Both are not what I want. I want 2nd column to keep 3 elements.
What's the best way to do it?
Thanks,
Jean
  4 Comments
Jean
Jean on 6 Feb 2012
Thanks, Walter. If the columns are fixed width, how will you do it?

Sign in to comment.

Answers (1)

Walter Roberson
Walter Roberson on 6 Feb 2012
For fixed width content:
fopen() the file.
Loop:
fgetl() a line. If ~ischar() the line, break out of the loop. Pad the line with blanks to a multiple of the field width (if need be). Call that Lin. Then,
L_by_field = reshape(Lin, FieldWidth, []) .';
blankfield = all(L_by_field == ' ',2);
L_by_field(blankfield,end-2:end) = 'NaN';
fieldvalues = str2double(cellstr(L_by_field));
Store the values, then let the loop continue.
When the loop finishes, fclose() the file.
  1 Comment
Jean
Jean on 6 Feb 2012
Walter, thanks. It works on the simple example I made, but doesn't work if I have data with different length. It gotta have a better way. Thanks anyway.
Jean

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices 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!