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

2 次查看(过去 30 天)
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 个评论

请先登录,再进行评论。

更多回答(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