error in using a function while using surf plot

4 views (last 30 days)
I am trying to plot a 3D plot using surf function im MATLAB.
I am using a calc fucntion and it gives an error "Z must be a matrix and not a scalar value".
Please help me resolve this error.
function fx = calc(x, const)
A = const(1);
B = const(2);
r = sqrt(x(1)^2 + x(2)^2);
fx = A * cos(r)^2 * exp(-B * r);
end
% Constants
A = 2;
B = 0.3;
% Coordinates
x = [3; 2];
% Evaluate the function at the given point
fx = calc(x, [A, B]);
% Define the range of x and y values
x_range = linspace(-10, 10, 100);
y_range = linspace(-10, 10, 100);
% Create a grid of points
[X, Y] = meshgrid(x_range, y_range);
% Evaluate the function at each point of the grid
Z = calc([X(:) Y(:)]', [A, B]);
surf(X,Y,Z)

Accepted Answer

Ronit
Ronit on 5 Jul 2023
The input in calc function is taking a matrix input which is creating this error. Instead of using x(1) and x(2), try using x(1,:) and x(2,:).
Since you are using an array and not a scalar value, you should use .^, .* and ./instead of ^,* and /.
Instead of sending an array input, I suggest you to input x, y separately
function fx = calc(x, y, const)
A = const(1);
B = const(2);
r = sqrt(X.^2 + Y.^2);
fx = A * cos(r).^2 .* exp(-B * r);
end
Then call the function:
Z = calc(x, y, [A, B]);
surf(X,Y,Z)

More Answers (0)

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!