MATLAB Answers

What is wrong I have been getting errors that it is wrong

18 views (last 30 days)
function output = impact(x,y)
output = sin(sqrt((x^2)+(y^2)))/sqrt((x^2)+(y^2));
x = -10:1:10;
y = -10:1:10;
z = output;
surfc(x,y,z) %Surface Plot
contour(x,y,z) %Contour lines
colormap(hsv)
Grid off
title('Impact Surface Plot')
xlabel('x-axis')
ylabel('y-axis')
zlabel('z-axis')
end
  1 Comment
KALYAN ACHARJYA
KALYAN ACHARJYA on 2 Mar 2021
The MATLAB executes code line by line (sequentially manner), defining the variables before using them in any expression. More follow the given answer.

Sign in to comment.

Accepted Answer

Star Strider
Star Strider on 2 Mar 2021
Try something like this:
outputfcn = @(x,y) sin(sqrt((x.^2)+(y.^2)))./sqrt((x.^2)+(y.^2));
x = linspace(-10, 10, 25);
y = linspace(-10, 10, 25);
[X,Y] = ndgrid(x,y);
z = outputfcn(X,Y);
figure
surfc(x,y,z) %Surface Plot
hold on
contour3(x,y,z) %Contour lines
hold off
colormap(hsv)
grid off
title('Impact Surface Plot')
xlabel('x-axis')
ylabel('y-axis')
zlabel('z-axis')
It is necessary to use element-wise opearations in the function, and the ndgrid or meshgrid functions to create the correct matrices, and the hold function to plot the surf and countour3 plots on the same axes. See Array vs. Matrix Operations for more information.
  1 Comment
Star Strider
Star Strider on 2 Mar 2021
It is necessary to create the matrices using ndgrid or meshgrid. Then it will work, draw the plotcs correctly, and return the matrices you want.
I would do something like this:
function [x,y,z] = impact
outputfcn = @(x,y) sin(sqrt((x.^2)+(y.^2)))./sqrt((x.^2)+(y.^2));
x = linspace(-10, 10, 50);
y = linspace(-10, 10, 50);
[X,Y] = ndgrid(x,y);
z = outputfcn(X,Y);
figure
surfc(x,y,z) %Surface Plot
hold on
contour3(x,y,z,'LineWidth',1.5) %Contour lines
hold off
colormap(hsv)
grid off
title('Impact Surface Plot')
xlabel('x-axis')
ylabel('y-axis')
zlabel('z-axis')
end
Then to see the result and recover the matrices:
[Xmtx,Ymtx,Zmtx] = impact; % Call The ‘impact’ Function
I would store them, not display them, since they will be huge matrices and will not easily be understandable just looking at the results.
If you want ‘impact’ to have input arguments, consider carefully what they should be and how to use them. One possibiolity is to provide the number of elements in the ‘x’ and ‘y’ vectors (those would be used as the third arguments to the linspace function calls), their limits, or all of these and possibly others as well.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!