Borrar filtros
Borrar filtros

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

2 visualizaciones (últimos 30 días)
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 comentarios
Thomas
Thomas el 6 de Jun. de 2012
I think this might be homework.. can you show what you have done so far?
Julius
Julius el 6 de Jun. de 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

Iniciar sesión para comentar.

Respuesta aceptada

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

Iniciar sesión para comentar.

Más respuestas (1)

Image Analyst
Image Analyst el 6 de Jun. de 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 comentario
Julius
Julius el 6 de Jun. de 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!

Iniciar sesión para comentar.

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by