0
votes

Given a matrix A, that has zeros on its diagonal and its lower triangular part:

A = triu(rand(5,5), 1) % example

A =
0.00000   0.47474   0.55853   0.30159   0.97474
0.00000   0.00000   0.03315   0.74577   0.20878
0.00000   0.00000   0.00000   0.54966   0.76818
0.00000   0.00000   0.00000   0.00000   0.82598
0.00000   0.00000   0.00000   0.00000   0.00000

I want to convert A into a compact vector v that skips all the zero elements:

v = [0.47474 0.55853 0.30159 0.97474 0.03315
     0.74577 0.20878 0.54966 0.76818 0.82598]

Later I want to convert from the vector back to the matrix.

Question: What is an elegant way to convert between these two representations?

3

3 Answers

6
votes

I would start with an upper triangular matrix of ones

B = triu(ones(5,5), 1)

And Then v can be defined as:

v = A(B==1)

Converting back from v to A

A = B
A(B==1) = v
1
votes

Because Matlab stores arrays in column-major order I couldn't do this in one statement, well not yet, but here's a two statement solution:

B = A';

v = B(B~=0)'

@dustincarr's answer renders further work by me redundant.

1
votes
A = triu(rand(5,5), 1);
v = reshape(nonzeros(A'), [5 2])';