Deepak kumar Jha
Deepak kumar Jha

Reputation: 524

What is the output of the following code in Matlab?

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

[~ ,im]=sort(reshape(a,1,[])'descend');

So what actually is im getting as output,it is not a sorted array?

Upvotes: 1

Views: 148

Answers (2)

mwengler
mwengler

Reputation: 2778

a = [1 2 3;4 5 6;7 8 9;];
A = reshape(a,1,[]);
[B ,im]=sort(A,'descend');

B is the sorted horizontal vector. im is the indexes so that all(A(im)==B) returns true.

You don't particularly need the reshape command, or rather another way to get the same result is

A = a(:)';

a(:) makes a column vector out of any array, and ' transposes that to a horizontal array. (' will also complex conjugate the elements of a if they are complex, but yours are not complex so this works here.)

I'm sort of surprised you are not looking for

B = sort(a,'descend'); 

which gives a 3x3 matrix output with each column sorted in descending order.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

Read the documentation; the second output parameter of sort is an array of indices, not an array of values.

Upvotes: 1

Related Questions