From: Nicholas on
I am looking to make a program where one of the output formulas is dependant on the value if the input. For example
x=1:10
For x>5 y=2*x
For x<5 y=3*x
I know there must be an obvious way to do this but i cant. Currently i am using the script
x=0:0.1:10;
>> if x>5
y=2*x
else
y=3*x
end
This only gives values of y=3*x regardless of the y value. Please help!!
From: Matt J on
"Nicholas " <n.ballard(a)warwick.ac.uk> wrote in message <hgqo18$768$1(a)fred.mathworks.com>...
> I am looking to make a program where one of the output formulas is dependant on the value if the input. For example
> x=1:10
> For x>5 y=2*x
> For x<5 y=3*x
> I know there must be an obvious way to do this but i cant. Currently i am using the script
> x=0:0.1:10;
> >> if x>5
> y=2*x
> else
> y=3*x
> end
> This only gives values of y=3*x regardless of the y value. Please help!!


y=(2*x).*(x>5) +(3*x).*(x<=5);
From: Andy on
% I'm not sure I completely understand what you're trying to do, but try this:

A=1:10; % fake data
v1=(A<5); % create an index vector
v2=(A>5); % create a second index vector
A(v1)=A(v1)*2;
A(v2)=A(v2)*3;
From: dpb on
Nicholas wrote:
> I am looking to make a program where one of the output formulas is
> dependant on the value if the input. For example
> x=1:10
> For x>5 y=2*x
> For x<5 y=3*x
> I know there must be an obvious way to do this....

One way..

y=zeros(size(x));
y(x>5) = 2*x(x>5);
y(x<5) = 3*x(x<5);

% the above, of course is what you literally asked for and leaves
% y(x==5) = 0; you'll have to choose what you want there...

Look up "logical indexing" in the online documentation for more...

--
From: Oleg Komarov on
Nicholas wrote in message
> I am looking to make a program where one of the output formulas is dependant on the value if the input. For example
> x=1:10
> For x>5 y=2*x
> For x<5 y=3*x
> I know there must be an obvious way to do this but i cant. Currently i am using the script
> x=0:0.1:10;
> >> if x>5
> y=2*x
> else
> y=3*x
> end
> This only gives values of y=3*x regardless of the y value. Please help!!

Nicholas,
since 'x' is a vector, 'if x' doesn't return a boolean value (true or false).
x=0:0.1:10;
IDX = x >= 5;
y = NaN(size(x));
y(IDX) = 2*x(IDX);
y(~IDX)= 3*x(~IDX);

Oleg
 |  Next  |  Last
Pages: 1 2
Prev: Code for cbir in matlab
Next: bpv4c problem