triu elements

How to get upper triangular elements as vector?

% Example matrix A

A=[1,2,3;4,5,6;7,8,9]

1 2 3

4 5 6

7 8 9

% define index of upper elements , triu: all above K=1 diagonal

idx = logical(triu(ones(size(A)), 1))

0 1 1

0 0 1

0 0 0

% extract as vector

v = A(idx)'

2 3 6

% convert back as matrix, if required

B=zeros(size(A));

B(idx)=v

0 2 3

0 0 6

0 0 0