From: Judas Magnus on
I need help writing 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.

I had this:

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

and I get

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


what am i doing wrong
From: Matt Fig on
You got that error message because when k = 1, y is set to pi (y is no longer a vector). You meant to set y(k) to pi. Think it through if that doesn't make sense. This is easier:

y = [1 2 3 4 5]
y = max(y,pi)
From: Nathan on
On Apr 20, 3:37 pm, "Judas Magnus" <ragnaork5...(a)yahoo.com> wrote:
> I need help writing 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.
>
> I had this:
>
> y = [1 2 3 4 5]
> for k = 1:length(y)
> if y(k) < pi
> y = pi
> end
> end
>
> and I get
>
> ??? Attempted to access y(2); index out of bounds because numel(y)=1.
>
> what am i doing wrong

For one, you are replacing the WHOLE array with one value (pi), when
instead you want to replace ONE value in the array with one value
(pi).

for k=1:length(y)
if y(k) < pi
y(k) = pi
end
end

A vectorized way to do this is as follows:
y = [1 2 3 4 5]
y(y<pi)=pi
%%%%%%%%%%%%
y =
3.1416 3.1416 3.1416 4.0000 5.0000

-Nathan
From: John D'Errico on
"Judas Magnus" <ragnaork5435(a)yahoo.com> wrote in message <hqlaaf$fs5$1(a)fred.mathworks.com>...
> I need help writing 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.
>
> I had this:
>
> y = [1 2 3 4 5]
> for k = 1:length(y)
> if y(k) < pi
> y = pi
> end
> end
>
> and I get
>
> ??? Attempted to access y(2); index out of bounds because numel(y)=1.
>
>
> what am i doing wrong

Why use an if statement at all?

help max
help min

John
 | 
Pages: 1
Prev: Mac electronic I/O
Next: skeleton code