How to have 'if statements' when defining 'constants'?

Hi guys,
I want to use 'if statements' to set certain constants in my surface. I have created this example of what I am trying to do. I want 'SomeConstant' to be a certain thing based on what the 'y' value is?
x = [0:100];
y = [0:100];
SomeConstant = 1;
if y <20
SomeConstant = 5;
else if y>20
SomeConstant = 10;
Test1 = @(x,y)(x+y)+SomeConstant;
Test2 = @(x,y)(x.^2+y)+SomeConstant;
[X1,Y1] = meshgrid(x,y);
Z1 = Test1(X1,Y1);
Z2 = Test2(X1,Y1);
s1 = surf(X1,Y1,Z1,'LineStyle','none');
hold on
s2 = surf(X1,Y1,Z2,'LineStyle','none');
Thank you

 Accepted Answer

I would create ‘SomeConstant’ as an anonymous function:
x = [0:100];
y = [0:100];
SomeConstant = @(y) [1*(y == 20) + 5*(y < 20) + 10*(y > 20)];
Test1 = @(x,y)(x+y)+SomeConstant(y);
Test2 = @(x,y)(x.^2+y)+SomeConstant(y);
[X1,Y1] = meshgrid(x,y);
Z1 = Test1(X1,Y1);
Z2 = Test2(X1,Y1);
s1 = surf(X1,Y1,Z1,'LineStyle','none');
hold on
s2 = surf(X1,Y1,Z2,'LineStyle','none');
You defined ‘SomeConstant’ to be 1, and then defined it as being 5 for y<20 and 10 for y>20. I created the anonymous function version with those conditions, adding the condition that it was 1 at y==20.
This works, but you have to determine if it produces the result you want.

4 Comments

Thanks for the answer. This is great. Can I ask for a modification with this. I like this:
SomeConstant = @(y) [1*(y == 20) + 5*(y < 20) + 10*(y > 20)];
But how can I make SomeConstant equal to 'y' if y is above 50?
Thanks
My pleasure.
Just add that as a condition:
SomeConstant = @(y) [1*(y == 20) + 5*(y < 20) + 10*((y > 20) & (y <= 50)) + y.*(y > 50)];
To verify that it works:
y = [0:100];
figure(1)
plot(y, SomeConstant(y))
grid
This all works. Thank you again! I will accept this answer!
My pleasure! Thank you!

Sign in to comment.

More Answers (0)

Asked:

A
A
on 3 May 2015

Commented:

on 3 May 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!