swapping two matrices with similar randomness
2 views (last 30 days)
Show older comments
I have two matrices.
I want the random change to be made in one matrix to be done in the same way in the other matrix. (note : my real matrix value is different from these)
For example:
A matrix:
1 2 3 4 5
B matrix :
0.1
0.2
0.3
0.4
0.5
Let's assume that the location of the matrix A has changed.
A matrix :
2 4 5 1 3
B matrix:
0.2
0.4
0.5
0.1
0.3
In other words, since the value of 1 is randomly assigned to the fourth column in the A matrix, the value of 0.1 is assigned to the fourth column.
Another example:
A matrix:
4 5 1 2 3
B matrix:
0.4
0.5
0.1
0.2
0.3
0 Comments
Answers (2)
John D'Errico
on 24 Mar 2022
You just need to learn how to use indexing.
A = [1 2 3 4 5];
B = zeros(5,2);
B(:,2) = A/10
Note that even thoiugh B(:,2) is a column vector, and A is a row vector, MATLAB is smart enough to see there are 5 elements to insert into B.
2 Comments
John D'Errico
on 24 Mar 2022
According to EVERY example you show, you would create B simply by dividing A by 10. While that may not be how you are thinking about it, that is EXACTLY the result you seem to want in your exampels.
A = [2 4 5 1 3];
B = A'/10
Feel free to tell me that is not exactly the result you showed you wanted. I would be forced to disagree, IF you did make some argument to that effect. So then if if you still think this does not do exactly what you want, then perhaps you can give a better example?
Voss
on 24 Mar 2022
If you are in control of how the rearranging is done to both matrices, you can create a vector of random indices and then index both matrices using that vector:
% initial state:
A = [1 2 3 4 5];
B = [0.1; 0.2; 0.3; 0.4; 0.5];
% generate the random index vector:
idx = randperm(numel(A))
% rearrange A and B in the same manner:
A_new = A(idx)
B_new = B(idx)
On the other hand, if you are not in control of how A is rearranged, but you need to rearrange B in the same way A was rearranged, you can do that too, if you have the original A:
% initial state:
A = [1 2 3 4 5];
B = [0.1; 0.2; 0.3; 0.4; 0.5];
% some process rearranges A randomly:
A_new = A(randperm(numel(A)))
% find idx, which tells you where each element of A_new was in A:
[~,idx] = ismember(A_new,A);
% rearrange B the same way to form B_new:
B_new = B(idx)
0 Comments
See Also
Categories
Find more on Logical 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!