error in using a function while using surf plot

3 ビュー (過去 30 日間)
Bond
Bond 2023 年 7 月 5 日
回答済み: Ronit 2023 年 7 月 5 日
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)

採用された回答

Ronit
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 件)

カテゴリ

Help Center および File ExchangeSurface and Mesh Plots についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by