Replacing vector/matrix elements in matlab

Discussion in 'Programmer's Corner' started by zulu, May 2, 2010.

  1. zulu

    Thread Starter New Member

    May 2, 2010
    1
    0
    hie all

    lets say i have y=[0 1 0 1]

    and want to replace the first element, y(1), with [0 0 0 0]

    is there a way of doing this

    plz help
     
  2. Ghar

    Active Member

    Mar 8, 2010
    655
    72
    y(1) refers to the very first number in that array, which is 0.

    You can't replace y(1) with a whole array unless y is a 'cell array'.

    You can write y(1) = 0, but since it's already 0 that won't do anything.
    You can change [0 1 0 1] to [0 0 0 0] in several ways.

    For example;
    y = [0 1 0 1]
    y(2) = 0
    You get: y = [0 0 0 1]
    y(4) = 0
    You get: y = [0 0 0 0]

    Or, you could just say:
    y = [0 0 0 0]
     
  3. johndoe45

    Member

    Jan 30, 2010
    364
    1
    should have said:

    lets say i have an array y=[0 1 0 1]

    and want to replace every 1 in the array y with 0

    therefore final output is y=[0 0 0 0]




    ok here we go

    y=[0 1 0 1];

    ones=find(y==1);

    y(ones)=0;

    y %matlab returns y=[0 0 0 0]
     
    Last edited: May 3, 2010
  4. t_n_k

    AAC Fanatic!

    Mar 6, 2009
    5,448
    782
    Unless you really wanted to know which particular array elements were "ones" or whether the array had non-zero elements, the exercise seems kind of pointless.

    Just setting the array to all zeros accomplishes the same result.

    why not simply write

    y=zeros(y)
     
Loading...