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

AI Thread Summary
The discussion focuses on replacing zeros in a matrix with elements from an array in Matlab, while also converting ones to zeros. A sample matrix ID is provided, and the goal is to transform it using an array EA. Participants share their code attempts, highlighting the use of nested loops to iterate through the matrix and replace values accordingly. The final solution involves maintaining a counter to track the position in the EA array while updating the matrix. The thread concludes with a successful implementation of the proposed solution.
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
 
Back
Top