How can I swap two elements in each row of a matrix without loops?

2 vues (au cours des 30 derniers jours)
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

Réponse acceptée

Fangjun Jiang
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

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by