Sorting a Matrix based on a identified vector.

6 Ansichten (letzte 30 Tage)
Mohannad Alzard
Mohannad Alzard am 2 Feb. 2021
Beantwortet: Arjun am 5 Dez. 2024
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 Kommentar
Jan
Jan am 2 Feb. 2021
I do not understand, what you want to achieve. While A(u) has the same value as u, what is the purpose of A?

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Arjun
Arjun am 5 Dez. 2024
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!

Kategorien

Mehr zu Shifting and Sorting Matrices finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by