Find answers, ask questions, and connect with our <br>community around the world.

• # Octave

Posted by on August 1, 2023 at 9:58 am

I wanted to understand how to plot this z=xe -(x2+y2)

2 Members · 2 Replies
• 2 Replies
• ### Sujith FTL

Member
August 1, 2023 at 1:00 pm

Hello Nishank,

You can refer the following code as example:

% Define the function to calculate z
function z = calculate_z(x, y, e)
z = x.^e – (x.^2 + y.^2);
end

% Create a grid of x and y values
x = linspace(-5, 5, 100);
y = linspace(-5, 5, 100);
[X, Y] = meshgrid(x, y);

% Choose a value for e (exponent)
e = 2;

% Calculate the corresponding z values for each (x, y) pair
Z = calculate_z(X, Y, e);

% Plot the 3D surface
figure;
surf(X, Y, Z);

xlabel(‘x’);
ylabel(‘y’);
zlabel(‘z’);
title([‘z = x^’, num2str(e), ‘ – (x^2 + y^2)’]);

% Set the view to isometric (azimuth = 35 degrees, elevation = 30 degrees)
view(35, 30);

Solution:

• ### Sujith FTL

Member
August 1, 2023 at 1:25 pm

Hello Nishank,

Sorry. I went through the actual question which was an assignment on CFD Foundation Course Lesson number 5 and found the question to be slightly different that you typed out. Please do mention lesson numbers and course name when you write in the forum so we can refer that particular lesson and assignment.

Here’s the updated code:

% Define the function z and its gradient
function z = calculate_z(x, y)
z = x .* exp(-x.^2 – y.^2);
end

function [gx, gy] = calculate_gradient(x, y)
gx = exp(-x.^2 – y.^2) – 2*x.^2 .* exp(-x.^2 – y.^2);
gy = -2*x.*y .* exp(-x.^2 – y.^2);
end

% Create a grid of x and y values
x = linspace(-3, 3, 100);
y = linspace(-3, 3, 100);
[X, Y] = meshgrid(x, y);

% Calculate the corresponding z values for each (x, y) pair
Z = calculate_z(X, Y);

% Calculate the gradients at each (x, y) point

% Plot the 3D surface
figure;
surf(X, Y, Z);

% Add labels and title for the surface plot
xlabel(‘x’);
ylabel(‘y’);
zlabel(‘z’);
title(‘z = x \cdot e^{-(x^2 + y^2)}’);

% Set the view to isometric (azimuth = 35 degrees, elevation = 30 degrees)
view(35, 30);

hold on;
quiver3(X, Y, Z, gx, gy, zeros(size(Z)), ‘color’, ‘r’, ‘linewidth’, 1.5);
hold off;