osimer pothe
osimer pothe

Reputation: 2897

how to read a row*col matrix from a file in MATLAB

I have the following data in a file .

1 3 5 
2 6 8
10 12 14
16 18 20 

I want to read it in a matrix by 4*3 dimension . Currently I am reading this matrix by the following code assuming the data is stored in the file named "A.txt".

A=textread('A.txt');

But the problem of this code is that if the file has any space at the last , MATLAB takes that input as zero . For example , if the file "A.txt" has a space after the data , by this piece of code , MATLAB takes input as the following :

1 3 5 
2 6 8
10 12 14
16 18 20 0

So I want to read the matrix as a row* col syntax . Can you please help me ?

Upvotes: 0

Views: 120

Answers (1)

Pablo EM
Pablo EM

Reputation: 6689

An option maybe is to capture the empty spaces as NaNs and after read the file remove the NaNs:

A = textread('A.txt','','emptyvalue',NaN)

A =

 1     3     5   NaN
 2     6     8   NaN
10    12    14   NaN
16    18    20   NaN

A = A(:,any(~isnan(A)))

A =

 1     3     5
 2     6     8
10    12    14
16    18    20

Upvotes: 1

Related Questions