Does surf() Behave as Expected with ndgrid() Inputs?
2 views (last 30 days)
Show older comments
Define a function
clear
f = @(x,y) x;
Case 1: square mesh, meshgrid, vector inputs to surf
x = 0:5;
y = 100:105;
[Xmesh,Ymesh] = meshgrid(x,y);
Zmesh = f(Xmesh,Ymesh);
figure
surf(x,y,Zmesh)
xlabel('x');ylabel('y')
Case 2: square mesh, ndgrid, vector inputs to surf
[Xnd,Ynd] = ndgrid(x,y);
Znd = f(Xnd,Ynd);
figure
surf(x,y,Znd)
xlabel('x');ylabel('y')
Cases 1 and 2 clearly indicate that the third input to surf should be built in meshgrid format consistent with the examples in the documentation.
What happens if using array inputs to surf?
Case 3: square mesh, meshgrid, array inputs to surf
figure
surf(Xmesh,Ymesh,Zmesh)
xlabel('x');ylabel('y')
Same result as Case 1, as expected
Case 4: square mesh, ndgrid, array inputs to surf
figure
surf(Xnd,Ynd,Znd)
xlabel('x');ylabel('y')
Why isn't Case 4 the same as Case 2?
0 Comments
Accepted Answer
Voss
on 6 Jun 2022
"Why isn't Case 4 the same as Case 2?"
Because Case 2 is erroneous. For vectors X and Y input to surf, matrix Z must be of size numel(Y)-by-numel(X).
Case 2 produces a surface because x and y happen to be the same length, but consider what happens when vectors x and y aren't the same length:
f = @(x,y) x;
x = 0:6;
y = 100:105;
[Xnd,Ynd] = ndgrid(x,y);
Znd = f(Xnd,Ynd);
% Case 2: square mesh, ndgrid, vector inputs to surf
figure
try
surf(x,y,Znd) % Znd is numel(x)-by-numel(y)
catch ME
disp(ME.message);
end
xlabel('x');ylabel('y')
% Case 2a (corrected): square mesh, ndgrid, vector inputs to surf
figure
surf(x,y,Znd.') % Znd.' is numel(y)-by-numel(x)
xlabel('x');ylabel('y')
% Case 4: square mesh, ndgrid, array inputs to surf
figure
surf(Xnd,Ynd,Znd)
xlabel('x');ylabel('y')
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!