Sorting a Matrix based on a identified vector.
3 ビュー (過去 30 日間)
古いコメントを表示
i would like to sort the following 4x4 matrix in an order as shown below:
for u=1:4
Block=randi([0,1],1,4);
Random(Rand1(u),:)=Block;
RandSorted(A(u),:)=???;
end
where Rand1=[3 2 4 1] and A=[1 2 3 4];,
i would like to resort it back to A instead of Rand1. thank you,
1 件のコメント
Jan
2021 年 2 月 2 日
I do not understand, what you want to achieve. While A(u) has the same value as u, what is the purpose of A?
回答 (1 件)
Arjun
2024 年 12 月 5 日
I understand that there is an array containing binary entries which is shuffled according to the order specified by vector “Rand1” and now you want to reorder the rows as per order specified by vector “A”.
To reorder the matrix back to the order specified by the vector A, you need to rearrange the rows that were initially shuffled using Rand1. The key operation is:
“RandSorted(A(u), :) = Random(Rand1 == A(u), :)” where “RandSorted” is the final answer matrix.
Below is the explanation of the above condition:
- A(u) gives the target position in the original order. For example, when u is 1, A(1) is 1, indicating that the first row in “RandSorted” should be filled.
- Rand1 == A(u) finds the position in Rand1 that corresponds to the current original order position A(u).
- Random(Rand1 == A(u), :) selects the row from Random that was initially at position A(u) before it was shuffled. This uses logical indexing to find the correct row.
- RandSorted(A(u), :) = ... assigns the selected row from Random to the correct position in “RandSorted”, effectively reversing the shuffle.
Kindly refer to the code below to have a better understanding:
% Initialization
Rand1 = [3 2 4 1];
A = [1 2 3 4];
Random = zeros(4, 4);
% Generate the random matrix and shuffle according to Rand1
for u = 1:4
Block = randi([0, 1], 1, 4);
Random(Rand1(u), :) = Block;
end
% Initialize the answer matrix
RandSorted = zeros(4, 4);
% Sort the matrix back to the order specified by A
for u = 1:4
RandSorted(A(u), :) = Random(Rand1 == A(u), :);
end
% Display the sorted matrix
disp(RandSorted);
I hope this will help!
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Shifting and Sorting Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!