Replace specific values in a matrix with zeros

조회 수: 13 (최근 30일)
Luan Nguyen Thanh
Luan Nguyen Thanh 2017년 11월 18일
댓글: Luan Nguyen Thanh 2017년 11월 18일
Assume, I have two matrices like this:
A =
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16
B = [3 2 4 5 2 1];
I want to produce a matrix C below from matrix A & B like this:
C =
35 1 6 26 19 24
3 32 7 21 23 0
31 0 2 22 0 0
0 0 33 17 0 0
0 0 0 12 0 0
where the ith element in matrix B determines "the number of elements in matrix A's ith column" that will bring to the ith column of the matrix C. For example, B(1) = 3 means that the 1st column of matrix C is equal to
[A(1:B(1),1) ; zeros(5-B(1),1)];
So is there any way for me to produce matrix C from A & B without using any "loop" command?

채택된 답변

Stephen23
Stephen23 2017년 11월 18일
편집: Stephen23 2017년 11월 18일
In one line:
>> A = [...
35 1 6 26 19 24
3 32 7 21 23 25
31 9 2 22 27 20
8 28 33 17 10 15
30 5 34 12 14 16];
>> B = [3,2,4,5,2,1];
>> C = A.*bsxfun(@le,(1:size(A,1)).',B)
C =
35 1 6 26 19 24
3 32 7 21 23 0
31 0 2 22 0 0
0 0 33 17 0 0
0 0 0 12 0 0
  댓글 수: 1
Luan Nguyen Thanh
Luan Nguyen Thanh 2017년 11월 18일
Oh, wow, it works perfectly, thank you very much.

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

추가 답변 (2개)

Bshara Murr
Bshara Murr 2017년 11월 18일
편집: Bshara Murr 2017년 11월 18일
Hello, yes try this:
A =[35 1 6 26 19 24; 3 32 7 21 23 25; 31 9 2 22 27 20; 8 28 33 17 10 15; 30 5 34 12 14 16;];
B = [3 2 4 5 2 1];
[x y]= size(A);
C = zeros(x,y);
for i = 1:y
for j = 1:B(i)
C(j,i) = A(j,i);
end
end
I just used the matrices you entered.

KL
KL 2017년 11월 18일
편집: KL 2017년 11월 18일
Try this,
[r c] = size(A);
C = zeros(r,c);
indx = bsxfun(@le,repmat((1:r).',1,c),repmat(B,r,1)) %find indicies
C(indx) = A(indx)
C =
35 1 6 26 19 24
3 32 7 21 23 0
31 0 2 22 0 0
0 0 33 17 0 0
0 0 0 12 0 0

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by