Filter löschen
Filter löschen

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

2 Ansichten (letzte 30 Tage)
Julius
Julius am 6 Jun. 2012
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 Kommentare
Thomas
Thomas am 6 Jun. 2012
I think this might be homework.. can you show what you have done so far?
Julius
Julius am 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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Image Analyst
Image Analyst am 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 Kommentar
Julius
Julius am 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!

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Get Started with MATLAB finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by