matlab single instruction

Discussion in 'Programmer's Corner' started by Judas543, Apr 20, 2010.

  1. Judas543

    Thread Starter Member

    Jan 26, 2010
    60
    0
    Write a single instruction that will take a vector y and change it such that any element of y that is less than pi is set to pi.

    Would it be like this

    y = [1 2 3 4 5]
    for k = 1:length(y)
    if y(k) < pi
    y = pi
    end
    end
     
  2. johndoe45

    Member

    Jan 30, 2010
    364
    1
    i think that is it. did you try it?
     
  3. Judas543

    Thread Starter Member

    Jan 26, 2010
    60
    0
    hmmm it says like a boundry error

    Attempted to access y(2); index out of bounds because numel(y)=1.
     
  4. johndoe45

    Member

    Jan 30, 2010
    364
    1
    try this. i have to go though. not on my pc computer. so can't run it for you

    y=[1 2 3 4 5]
    for i=1:length(y)
    if y(i)< pi
    y(i)=pi
    end
    end
    y %to see if it is correct


    or this one!

    y=[1 2 3 4 5]
    for i=1:length(y)
    if y< pi
    y(i)=pi
    end
    end
    y %to see if it is correct

    if not i don't even think need for loop. just

    y=1:5;
    if y<pi
    y=pi
    end
    y %to see if it is correct
     
    Last edited: Apr 20, 2010
  5. Judas543

    Thread Starter Member

    Jan 26, 2010
    60
    0
    first one worked out well, and i found out what i did wrong :p

    I replaced the whole array with the value (pi),
    instead of replacing one value in the array with one value
    (pi).

    Thanks!
     
Loading...