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

조회 수: 1 (최근 30일)
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

채택된 답변

Fangjun Jiang
Fangjun Jiang 2021년 4월 8일
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개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by