Whizkid95
Whizkid95

Reputation: 271

How to plot a surface plot with constraints

I'm trying to plot a function subject to three constraints (see code)

Now I tried the following

function value = example(x1, x2)

if x1 < 0 || x2 < 0 || x1+2*x2 > 6
    value = NaN;
else 
    value = abs(x1 - x2) + exp(-x1 - x2); 
end

[X, Y] = meshgrid(-10:10, -10:10);
Z = example(X,Y);
surf(X, Y, Z)

Now, this raises an error since the if clause cannot be evaluated for inputs X and Y. Any idea how to make this work?

Upvotes: 1

Views: 359

Answers (1)

Banghua Zhao
Banghua Zhao

Reputation: 1556

As @Cris mentioned, use logical indexing.

The basic idea is (x1 < 0 | x2 < 0 | x1+2*x2 > 6) will gives you a matrix (same size as value) of zeros and ones. The positions of ones correspond to the true condition. Try this:

function value = example(x1, x2)
value = abs(x1 - x2) + exp(-x1 - x2); 
value(x1 < 0 | x2 < 0 | x1+2*x2 > 6) = NaN;

Output:

enter image description here

Upvotes: 1

Related Questions