i m trying interpret this simple matrix code..
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
0 commentaires
Réponse acceptée
Voss
le 30 Avr 2022
rand('seed',345)
B=randi([-150,300],10,7)
[sorted_B_column_3,old_indices_in_B_column_3]=sort(B(:,3))
%using [y,in] this two variables because this is matrix with line,row
%so i m usinng two variables right?
% it's two variables because that's two outputs from the sort() function:
% (1) the sorted values, and (2) the index where each value was in the
% original (unsorted) array
%
% for instance, in this case:
% old_indices_in_B_column_3(1) is 2, which tells you that element #2 (-112) in column 3 of B is the smallest
% old_indices_in_B_column_3(2) is 9, which tells you that element #9 (-70) in column 3 of B is the next smallest
% etc.
%and i can change 'y','in' to another chracters right?
% yes, you can use any valid variable name, or use ~ if you don't need that
% output, e.g., [~,idx] = sort(B(:,3));
Plus de réponses (1)
Riccardo Scorretti
le 30 Avr 2022
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).
Voir également
Catégories
En savoir plus sur Get Started with MATLAB dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!