How can I swap two elements in each row of a matrix without loops?
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Jack Rolf-Gokes
le 8 Avr 2021
Réponse apportée : Fangjun Jiang
le 8 Avr 2021
If I have, say, a 5x4 matrix, and for each row I want to randomly select two elements and swap them, is there any way of doing this without using loops?
For example (A is the input, B is an example output):
A =
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
B =
1 3 2 4
7 6 5 8
9 10 12 11
13 14 16 15
17 20 19 18
0 commentaires
Réponse acceptée
Fangjun Jiang
le 8 Avr 2021
This is lengthy but does the job.
%%
flag=logical([0 0 1 1]); % pick two elements in each row
p=perms(flag); % all the possible permutation, total is 24
index1=randi(24,5,1); % pick 5 random numbers from 1 to 24
index=p(index1,:); % this is the logical index to pick the numbers in each row
A=reshape(1:20,5,4)% original matrix
B=A'; % need to transpose
data=B(index');
data=reshape(data,2,[]) %pick out the data, each column contains two numbers from each row in the matrix A
data=data([2,1],:) % swap
B(index')=data; % fill back the data
B=B' % transpose, this is the result
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical 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!