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

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 3K views
quetzal
Messages
5
Reaction score
0

Homework Statement


I have a matrix that contains zeros but it may contain also ones. For example:
Code:
                   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:
EA=1:8;        ID=[0 2 5 7;
                   1 3 6 8;
                   0 4 0 0]

Homework Equations


The Attempt at a Solution


I tried it this way but don't know how to finish it:
Code:
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:
Physics news on Phys.org
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
 
Awesome! I've got it done similarly...Thanks!
num=1;

Code:
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