Plot a multivariable function in Matlab

865 Views Asked by At

Let $f:\mathbb{R}^2 \to \mathbb{R}_+$ be the function defined piecewise by $$ f(x,y) := \begin{cases} \sqrt{1 - x^2 - y^2} &\text{, if } x^2+y^2 \leq 1 \text{ and } y \geq 0, \\ 0 &\text{, otherwise.} \end{cases} $$

I would like to plot this function in MATLAB. I tried the following code, but only recieve error notifications... (I suspect mistakes in the definition of f and/or the line with Z);

f = @(x,y) piecewise(x^2+y^2<=1, piecewise(y>=0,sqrt(1-x^2-y^2),y<0,0), x^2+y^2>1, 0);
        
xarray = linspace(-5,5,51);
yarray = linspace(-5,5,51);
[X,Y] = meshgrid(xarray,yarray);
Z = f(xarray,yarray);
    
% Plot the function %
figure
surfc(X,Y,Z)
xlabel('x')
ylabel('y')
zlabel('f(x,y)')
colorbar

Thanks in advance for any help! :)

1

There are 1 best solutions below

1
On BEST ANSWER

Two different naive approaches (they are naive because they don't rigorously treat discontinuities):

xmin = -1.5; xmax = -xmin; xpto = 500;                               % creating 2D domain for your function..
ymin = -1.5; ymax = -ymin; ypto = 500;                               % creating 2D domain for your function..
[X,Y] = meshgrid(linspace(xmin,xmax,xpto),linspace(ymin,ymax,ypto)); % creating 2D domain for your function..

FXY_1 = sqrt(1-X.^2-Y.^2); % f1 values..
FXY_2 = 0*X;               % f2 values..

FXY_1_CONDITION = ( X.^2 + Y.^2 ) <= 1 & Y >= 0; % f1 domain..
FXY_2_CONDITION = ~FXY_1_CONDITION;              % f2 domain..

FXY_1(FXY_2_CONDITION) = NaN; % ignoring f2 domain in f1 (NaN values are ignored by plot function)...
FXY_2(FXY_1_CONDITION) = NaN; % ignoring f1 domain in f2 (NaN values are ignored by plot function)...

figure('color','white');
hold on;
mesh(X,Y,FXY_1); % plot f1..
mesh(X,Y,FXY_2); % plot f2..
colorbar;

.

xmin = -1.5; xmax = -xmin; xpto = 500;                               % creating 2D domain for your function..
ymin = -1.5; ymax = -ymin; ypto = 500;                               % creating 2D domain for your function..
[X,Y] = meshgrid(linspace(xmin,xmax,xpto),linspace(ymin,ymax,ypto)); % creating 2D domain for your function..

FXY = NaN .* X;            % initializing f..
FXY_1 = sqrt(1-X.^2-Y.^2); % f1 values..
FXY_2 = 0 .* X;            % f2 values..

FXY_1_CONDITION = ( X.^2 + Y.^2 ) <= 1 & Y >= 0; % f1 domain..
FXY_2_CONDITION = ~FXY_1_CONDITION;              % f2 domain..

FXY(FXY_1_CONDITION) = FXY_1(FXY_1_CONDITION); % passing f1 values to f..
FXY(FXY_2_CONDITION) = FXY_2(FXY_2_CONDITION); % passing f2 values to f..

figure('color','white');
mesh(X,Y,FXY); % plot f..
colorbar;