Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: sorting in rows

Tags:

sorting

matlab

Why does this

t = magic(4);
k = 1:4;
tt(k,:) = sort(t(k,:)) % 

sort values inside each column (swapping rows and cols does nothing), but this

t = magic(4);
for k = 1:4
  tt(k,:) = sort(t(k,:))
end

sorts values inside row, as expected?

like image 216
z3dd Avatar asked Dec 06 '22 18:12

z3dd


1 Answers

In the following

t = magic(4);
k = 1:4;
tt(k,:) = sort(t(k,:)) % 

t(k,:) is a 4x4 matrix. Hence, sort will apply its default 1-dim sorting, i.e., w.r.t. rows. Note that you can tell sort to sort along the 2nd dimension. i.e., w.r.t. columns, by

tt(k,:) = sort(t(k,:),2)

In your other case, k is an integer and t(k,:) is a 1x4 row vector; hence, sorting will be performed w.r.t. columns.

t = magic(4);
for k = 1:4
  tt(k,:) = sort(t(k,:))
end

Finally, take note of @Luis Mendo:s clarification in the comments below, which I include here in case the comment were to be removed:

Just a clarification: by default sort (like most Matlab functions), doesn't work along the first dim, but along the first non-singleton dim. The distinction is important if the input matrix can be a row vector.

like image 69
dfrib Avatar answered Jan 11 '23 13:01

dfrib