필터 지우기
필터 지우기

Shuffling non-zero elements of each column in a matrix

조회 수: 1 (최근 30일)
Antonio
Antonio 2018년 4월 13일
댓글: Antonio 2018년 4월 13일
I want to shuffle non-zero elements of each column in a matrix but keep the zero elements at the same place. Like I have this:
A =
[10 0 30 40 50 60
11 0 31 41 0 61
0 22 32 42 0 62
13 23 0 43 0 63
0 24 34 44 54 64
15 0 35 0 0 65
16 26 36 46 56 66]
And I want this:
B =
[13 0 32 44 54 64
11 0 35 42 0 63
0 24 36 40 0 61
16 23 0 43 0 62
0 22 31 41 56 60
10 0 30 0 0 66
15 26 34 46 50 65]
So herein I have the zeros at the exact same place (i.e. ~A = ~B) and the non-zero elements are shuffled. Obviously shuffling the columns using 'randperm' does not work as it does not allow me to keep zeroes at the same place!

채택된 답변

James Tursa
James Tursa 2018년 4월 13일
편집: James Tursa 2018년 4월 13일
You're probably going to need a loop for this since the number of non-zero elements in a column is not constant across all the columns. For each column, use randperm on the non-zero elements. E.g., the process for one column:
A = your matrix
Ac = A(:,1); % a column
z = Ac ~= 0; % the non-zero element logical indexes
Az = Ac(z); % the non-zero elements
A(z,1) = Az(randperm(numel(Az))); % the shuffled elements replaced
Or, if you want a new matrix B as a result then copy A into B first and operate on B.
  댓글 수: 3
James Tursa
James Tursa 2018년 4월 13일
Put everything in the loop, not just the last two lines. Change the 1 to your loop index variable.
Antonio
Antonio 2018년 4월 13일
@James Tursa Oh man .. since you didn't put it in a loop yourself I thought it is way more complicated than that lmao. Thanks a bunch anyway it works perfect!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by