user3727281
user3727281

Reputation: 131

How to sort an arrange value in vector in Matlab?

Assume that we have a vector as

A = [ 0 0 0 0 -1 2 -5 4 5 3 9 0 0 0 0 0]

How to sort a matrix with the value is increasing, and it could be become as

A = [0 0 0 0 -5 -1 2 3 4 5 9 0 0 0 0 0]

Thanks a lot,

Upvotes: 1

Views: 66

Answers (1)

sco1
sco1

Reputation: 12214

You can use logical indexing and sort.

For example, assuming only 1 "island" of non-zeros:

A = [ 0 0 0 0 -1 2 -5 4 5 3 9 0 0 0 0 0];

A(A~=0) = sort(A(A~=0));

Returns:

>> A

A =

     0     0     0     0    -5    -1     2     3     4     5     9     0     0     0     0     0

Upvotes: 4

Related Questions