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

1. Jun 6, 2012

### quetzal

1. The problem statement, all variables and given/known data
I have a matrix that contains zeros but it may contain also ones. For example:
Code (Text):

ID=[1 0 0 0;
0 0 0 0;
1 0 1 1]

I'm trying to replace all the ones by zeros and all the zeros by elements of an array EA going column-wise so that the resulting matrix ID would look like:
Code (Text):

EA=1:8;        ID=[0 2 5 7;
1 3 6 8;
0 4 0 0]

2. Relevant equations
3. The attempt at a solution
I tried it this way but don't know how to finish it:
Code (Text):

D=3;
N=4;
ID=zeros(D,N);
equations=sum(ID(:)==0);% number of zeros in matrix ID
EA=1:equations;

for j=1:N
for i=1:D
if ID(i,j)==1
ID(i,j)=0;
else
ID(i,j)=?????;
end
end
end

Last edited: Jun 6, 2012
2. Jun 6, 2012

### qizzlestick

you could make a separate variable say num for EA and do this
num=1;

for j=1:N
for i=1:D
if ID(i,j)==1
ID(i,j)=0;
else
ID(i,j)=EA(1,num);
num+=1;
end
end
end

3. Jun 6, 2012

### quetzal

Awesome! I've got it done similarly...Thanks!
num=1;

Code (Text):

for j=1:N
for i=1:D
if ID(i,j)==1
ID(i,j)=0;
else
ID(i,j)=EA(num);
num=num+1;
end
end
end