edgarmtze
edgarmtze

Reputation: 25038

How to load this kind of matrix in MATLAB

I have an upper triangular matrix like:

A=  load('A.txt');

1.0    3.32   -7.23
       1.00    0.60
               1.00

I want to load it in MATLAB, and as this is symmetric converting it doing

a = A + triu(A, 1)'
so at the end I will have a matrix a

1.0    3.32   -7.23
3.32   1.00    0.60
-7.23  0.60    1.00

the problem I am having is at the moment of loading:

>> A = load('A.txt');
??? Error using ==> load
Number of columns on line 1 of ASCII file C:\A.txt
must be the same as previous lines.

Is there a way to accomplish this?

Upvotes: 1

Views: 3652

Answers (1)

Ghaul
Ghaul

Reputation: 3330

Try using importdata instead, load is usually only used for .mat files. How is your file A.txt structured? If it is like this,

1.0    3.32   -7.23
1.00    0.60
1.00

then you will get

A = importdata('A.txt')

A =

    1.0000    3.3200   -7.2300
    1.0000    0.6000       NaN
    1.0000       NaN       NaN

So you will have to shift the two last rows, like this

A(2,:) = circshift(A(2,:),[0 1])
A(3,:) = circshift(A(3,:),[0 2])

A =

    1.0000    3.3200   -7.2300
    NaN       1.0000    0.6000
    NaN       NaN       1.0000

and then replace the NaNs with 0s and use your expression to create a symmetric matrix.

A(isnan(A)) = 0;

a = A + triu(A, 1)';

A =

    1.0000    3.3200   -7.2300
    3.3200    1.0000    0.6000
   -7.2300    0.6000    1.0000

Upvotes: 5

Related Questions