error in using a function while using surf plot
조회 수: 2 (최근 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에서 Surface and Mesh Plots에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!