1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

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

  1. Jun 6, 2012 #1
    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. jcsd
  3. Jun 6, 2012 #2
    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
     
  4. Jun 6, 2012 #3
    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
     
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: How to replace zeros in a matrix by elements of an array in Matlab?
Loading...