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
Question
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?
Solution
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
OTHER TIPS
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.
A = triu(rand(5,5), 1);
v = reshape(nonzeros(A'), [5 2])';