error in using a function while using surf plot
5 次查看(过去 30 天)
显示 更早的评论
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)
0 个评论
采纳的回答
Ronit
2023-7-5
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)
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Annotations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!