Hello everybody,
I have a question regarding the sorting. I have 2 matrices, A and B. For example:
A = [11 1; 12 1; 13 1; 21 2; 23 2; 31 3; 33 3; 41 4]
B = [1; 2; 1; 3; 1; 4; 2; 3]
How can I sort A (randomly each time) that the 2 column of A is same with B? Such as:
A = [12 1; 23 2; 11 1; 31 3; 13 1; 41 4; 21 2; 33 3]
Stay happy and healty..

 採用された回答

Stephen23
Stephen23 2020 年 9 月 16 日

2 投票

>> [~,idx] = sort(B);
>> [~,idx(idx)] = sort(A(:,2));
>> A = A(idx,:)
A =
11 1
21 2
12 1
31 3
13 1
41 4
23 2
33 3

6 件のコメント

Doli Swey
Doli Swey 2020 年 9 月 16 日
Thank you very much Stephan. This do what I want. However, it always sort in acending order. Is there any way to make this random?
Stephen23
Stephen23 2020 年 9 月 16 日
編集済み: Stephen23 2020 年 9 月 16 日
"Is there any way to make this random"
Ah, I missed that part of the question. Give me a few minutes.
EDIT: probably a simple loop is the best approach:
A = [11,1;12,1;13,1;21,2;23,2;31,3;33,3;41,4]
B = [1;2;1;3;1;4;2;3]
C = B(:,[1,1]);
for k = 1:max(B)
X = find(B==k);
X = X(randperm(numel(X)));
C(X,:) = A(A(:,2)==k,:);
end
Giving:
>> C
C =
12 1
23 2
11 1
31 3
13 1
41 4
21 2
33 3
Doli Swey
Doli Swey 2020 年 9 月 16 日
Yes!. Thank you very much Stephan. All best..
Doli Swey
Doli Swey 2020 年 10 月 17 日
編集済み: Doli Swey 2020 年 10 月 17 日
Hello again Stephan, I have a problem regarding to
A (:, 2) == k
Since my A is a string array and k is double, I cannot proceed.
I have attached the A variable (CombinedStim).
I tried to use str2double and got NAN values ​​because the first column contains strings, whereas second column is numbers.
Then i try regexp, however I was not succesfull again.
Do you have any idea that I can make this work?
Stephen23
Stephen23 2020 年 10 月 17 日
編集済み: Stephen23 2020 年 10 月 17 日
"Do you have any idea that I can make this work?"
Possibly you could replace the RHS with a string (or character vector) of the number:
A(:,2) == num2str(k)
"...the first column contains strings, whereas second column is numbers."
I strongly recommend that you convert the data into a table, then the first column would be strings and the second column really would be numbers (not strings encoding numbers). Numeric data should be efficiently stored as numeric, which also makes processing it much easier.
Doli Swey
Doli Swey 2020 年 10 月 19 日
I understand! Thank you so much. Have a wonderful day

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeTables についてさらに検索

タグ

質問済み:

2020 年 9 月 15 日

コメント済み:

2020 年 10 月 19 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by