필터 지우기
필터 지우기

How to replace zeros in a matrix by the elements of an array?

조회 수: 2 (최근 30일)
Julius
Julius 2012년 6월 6일
Hi everybody! I have a matrix (A) that contains zeros but it may contain also ones.
R=1:8; A=[1 0 0 0;
0 0 0 0;
1 0 1 1]
How to replace all the ones by zeros and all the zeros by elements of an array (R) going column-wise so that the resulting matrix (B) would look like:
B=[0 2 5 7;
1 3 6 8;
0 4 0 0]
  댓글 수: 2
Thomas
Thomas 2012년 6월 6일
I think this might be homework.. can you show what you have done so far?
Julius
Julius 2012년 6월 6일
Yes, I've done this:
D=3;
N=4;
A=zeros(D,N);
equations=sum(A(:)==0);
R=1:equations;
for j=1:N
for i=1:D
if A(i,j)==1
A(i,j)=0;
else
ID(i,j)=?????;
end
end
end
B=A
....but I don't know how to continue

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

채택된 답변

Thomas
Thomas 2012년 6월 6일
You are on the right track, though it can be done in much simpler way but since you are a beginner this will suffice..
use
Your input matrix was zeros, just add a count for R values
Editing your code:
A=[1 0 0 0;
0 0 0 0;
1 0 1 1]
D=3;
N=4;
% A=zeros(D,N);
equations=sum(A(:)==0);
R=1:equations;
count=1;
for j=1:N
for i=1:D
if A(i,j)==1
A(i,j)=0;
else
ID(i,j)=R(count);
count=count+1;
end
end
end
ID
  댓글 수: 3
Thomas
Thomas 2012년 6월 6일
count is a variable.. I'm incrementing it every iteration..
Julius
Julius 2012년 6월 6일
I see.....that's why I didn't find such command. Very clever!

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

추가 답변 (1개)

Image Analyst
Image Analyst 2012년 6월 6일
R=1:8;
A=[1 0 0 0;
0 0 0 0;
1 0 1 1]
linearIndices = A == 0
B = A; % Make a copy.
B(A==1) = 0
B(linearIndices) = R;
This is a vectorized way of doing it rather than your for loop method.
  댓글 수: 1
Julius
Julius 2012년 6월 6일
I just wanted to write down that the answer for your question is: B(A==0)=R.Meanwhile, you have done it instead of me. I just tried it and it worked. It wouldn't even cross my mind to do it that way. And it seems to be a faster code than the mine one. Thank you!

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

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by