Problem with matrix size when using importdata

4 views (last 30 days)
Hello,
I am trying to import a matrix from a text file, but a strange problem occured:
The matrix in question is
2 2 3 2
2 2 1 1
1 0
2 4
1 1 2 200000 80000
However, when I try to import it, it is imported with only 4 columns
2 2 3 2
2 2 1 1
1 0 NaN NaN
2 4 NaN NaN
1 1 2 200000
80000 NaN NaN NaN
What I was able to do is make it be imported correctly, but only if I change the original matrix to
1 1 2 200000 80000
2 2 3 2
2 2 1 1
1 0
2 4
But the input is not changeable, and I can't change the rows' position after reading it and before using, since it already reads incorrectly.
Could anyone help me?
Thanks a lot in advance!

Answers (1)

dpb
dpb on 11 Jun 2013
What did you use to read the file?
Obviously, when the record length changes in the middle, this is going to confuse any of the simpler reading schemes that parse the first record and go from there.
If you can't create the file to be regular then you'll have to read it a line at a time and parse each. fgetl() may be your friend here altho textscan() can also be called for the same fid repetitively.
  3 Comments
Alan
Alan on 22 Jun 2013
Edited: Alan on 22 Jun 2013
I could not use these properly. No offense, but this seems to be way more than I need. It is just one program for school, and I will never use MATLAB again. I wonder if it is possible just to add a zero on the last position in first row, then I would have a five-column matrix. Can I easily open the file in MATLAB, add a zero, close it, then run my program? (Leaving the matrix like that:
2 2 3 2 0
2 2 1 1
1 0
2 4
1 1 2
200000 80000)
Thanks a lot
dpb
dpb on 22 Jun 2013
You can open and edit the file in any text editor (the Matlab one is fine) and manually edit the file, sure. But, that's the kludgy way 'round. Why can't you create the file w/ a consistent number of columns to begin with, though?
But, if you do edit it manually, you'll have to add a value to the 2nd row, three to the 3rd/4th/6th and two to the 5th. And unless you code it for a missing value, how will you know inside Matlab which is good/bad data? Not the ideal solution I'd think.
And, while you may think you'll "never use Matlab again", you almost certainly will need some other programming toolset and the skills learned of solving such problems carry over in principle to many areas even if the absolute precise keystrokes don't.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!