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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With