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

6 views (last 30 days)
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 Comments
Thomas
Thomas on 6 Jun 2012
I think this might be homework.. can you show what you have done so far?
Julius
Julius on 6 Jun 2012
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

Sign in to comment.

Accepted Answer

Thomas
Thomas on 6 Jun 2012
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 Comments
Thomas
Thomas on 6 Jun 2012
count is a variable.. I'm incrementing it every iteration..
Julius
Julius on 6 Jun 2012
I see.....that's why I didn't find such command. Very clever!

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 6 Jun 2012
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 Comment
Julius
Julius on 6 Jun 2012
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!

Sign in to comment.

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!