i m trying interpret this simple matrix code..
Show older comments
seed:345
10x7 matrix,
[-150,300]
B=randi...
and i want to sort 10 elements of row3 by ascending order.
i m wondering >>> %parts!
>> rand('seed',345)
>> B=randi([-150,300],10,7)
B =
-148 86 -67 36 -15 -141 195
-38 177 41 124 266 74 284
27 95 32 107 45 204 206
76 182 11 269 -78 -80 -100
-34 275 -138 238 -48 20 15
171 -119 88 108 -79 195 -118
19 134 12 76 -35 -131 138
285 228 -78 148 -9 -107 -55
225 23 147 20 -73 155 237
-18 247 279 17 277 222 71
>> [y,in]=sort(B(:,3)) %using [y,in] this two variables because this is matrix with line,row
%so i m usinng two variables right?
%and i can change 'y','in' to another chracters right?
y =
-138
-78
-67
11
12
32
41
88
147
279
in =
5
8
1
4
7
3
2
6
9
10
>> B(in(1:end),:)
ans =
-34 275 -138 238 -48 20 15
285 228 -78 148 -9 -107 -55
-148 86 -67 36 -15 -141 195
76 182 11 269 -78 -80 -100
19 134 12 76 -35 -131 138
27 95 32 107 45 204 206
-38 177 41 124 266 74 284
171 -119 88 108 -79 195 -118
225 23 147 20 -73 155 237
-18 247 279 17 277 222 71
Accepted Answer
More Answers (1)
rand('seed',345);
B = randi([-150,300], 10, 7);
[y,in] = sort(B(:,3));
You are sorting a column vector (= the 3rd column of B). The output are:
- y = sorted vector
- in = index such that y = B(in,3)
y'
B(in,3)'
It doen't matter whether you are sorting a column vector, a matrix of whatever: ask for two output arguments if you need to know the index (sometimes it is an important information).
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!