How can I create a surface plot of a function of 3 variables?

I have the following function that describes a quadric surface:
syms f(x, y, z)
f(x, y, z) = -x^2 - (y^2 / 4) + (z^2 / 4) == 1
I'm trying to understand how to plot it. I've tried a few things, like solving the equation for z, and then filling in a matrix containing z values. e.g.
syms g(x, y);
g(x, y) = solve(f(x, y, z), z); % matrix([[-(4*x^2 + y^2 + 4)^(1/2)], [(4*x^2 + y^2 + 4)^(1/2)]])
xrange = -10:10;
yrange = -10:10;
zrange = zeros(numel(xrange), numel(yrange));
for i = 1:numel(xrange)
for j = 1:numel(yrange)
zrange(i, j) = g(xrange(i), yrange(j));
end
end
Unfortunately, this code does not because z can take on multiple values for a given (x, y) value. MATLAB rightly complains:
Assignment has more non-singleton rhs dimensions than non-singleton subscripts
Any tips? Do I need to make xrange and yrange into matrix values? If so, then what should they look like? If not, then what are some other things I can look into?
Thanks.

Answers (2)

syms f(x, y, z)
f(x, y, z) = -x^2 - (y^2 / 4) + (z^2 / 4) == 1
syms g(x, y);
g(x, y) = solve(f(x, y, z), z); % matrix([[-(4*x^2 + y^2 + 4)^(1/2)], [(4*x^2 + y^2 + 4)^(1/2)]])
xrange = -10:10;
yrange = -10:10;
zrange = zeros(numel(xrange), numel(yrange));
for i = 1:numel(xrange)
for j = 1:numel(yrange)
a=g(xrange(i), yrange(j));
zrange1(i, j) = double(a(1));
zrange2(i,j)=double(a(2));
end
end
close
surf(xrange,yrange,zrange1)
hold on
surf(xrange,yrange,zrange2)

1 Comment

Thanks Azzi. That's helpful, but is there a way I can make it generic for other functions? For example, what if f is defined as such:
f(x, y, z) = 4*x + 7*y - 6*z - 8 == 0
In this case, z will only have 1 value at every point.
I noticed the surf() function is able to plot surfaces with multiple values at a given (x, y) value (e.g. sphere()), so this seems like a possible avenue to explore. However, I'm not clear about how the matrices for X and Y should look in that case.

Sign in to comment.

I suggest you use isosurface over a meshgrid of x, y, z

1 Comment

Thanks. It does look promising, but I'd appreciate an example using the function the way I defined it. The MATLAB docs don't show any such examples.

Sign in to comment.

Products

Tags

Asked:

on 29 Apr 2016

Commented:

on 30 Apr 2016

Community Treasure Hunt

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

Start Hunting!