How to plot gradients ?

 Accepted Answer

Star Strider
Star Strider on 1 Oct 2020

2 votes

14 Comments

qweasd
qweasd on 1 Oct 2020
Edited: qweasd on 1 Oct 2020
thanks, I've seen this page but I still can't do it. I am new in Matlab.
This should get you started:
x = linspace(3, 4, 25);
y = linspace(5, 6, 25);
[X,Y] = meshgrid(x,y);
z = @(x,y) x.^2+y.^5+3*x+4*y;
Z = z(X,Y);
See the documentation section on Anonymous Functions to understand ‘z’.
You can also use ndgrid instead of meshgrid.
It is not a very interesting plot.
Thank you, I will try it.
My pleasure!
I've been working on it, but still cant do it. I'm really bad :( If you don't mind, can you share the code?
You aren’t really bad. You simply need to experiment with it.
The rest of the code is essentially what’s in the documentation example that I linked to, from the gradient call to the end of the example. You only need to make a few small changes to it.
qweasd
qweasd on 5 Oct 2020
Edited: qweasd on 5 Oct 2020
x = linspace(3, 4, 25);
y = linspace(5, 6, 25);
[X,Y] = meshgrid(x,y);
z = @(x,y) x.^2+y.^5+3*x+4*y;
Z = z(X,Y);
[px,py] = gradient(Z)
figure
contour(x,y,Z)
hold on
quiver(x,y,px,py)
hold off
Like this ?
Like that!
The code I wrote for your problem:
x = linspace(3, 4, 25);
y = linspace(5, 6, 25);
[X,Y] = meshgrid(x,y);
z = @(x,y) x.^2+y.^5+3*x+4*y;
Z = z(X,Y);
[px,py] = gradient(Z);
figure
contour(X,Y,Z)
hold on
quiver(X,Y,px,py)
hold off
They appear to match.
thank you so much
As always, my pleasure!
x = linspace(3, 4, 25);
y = linspace(5, 6, 25);
[X,Y] = meshgrid(x,y);
z = @(x,y) x.^2+y.^5+3*x+4*y;
Z = z(X,Y);
[px,py] = gradient(Z);
figure
contour(X,Y,Z)
hold on
quiver(X,Y,px,py)
hold off
it's not working
Yes, it is!
x = linspace(3, 4, 25);
y = linspace(5, 6, 25);
[X,Y] = meshgrid(x,y);
z = @(x,y) x.^2+y.^5+3*x+4*y;
Z = z(X,Y);
[px,py] = gradient(Z);
figure
contour(X,Y,Z)
hold on
quiver(X,Y,px,py)
hold off
.
Niklas Kurz
Niklas Kurz on 13 Mar 2022
Edited: Niklas Kurz on 13 Mar 2022
I would opt to normalise the Arrows for better scaling:
Norm = sqrt(px.^2+py.^2)
quiver(X,Y,px./Norm,py./Norm,0.5)
Otherwise the code is pretty neat!

Sign in to comment.

More Answers (0)

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Asked:

on 1 Oct 2020

Edited:

on 13 Mar 2022

Community Treasure Hunt

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

Start Hunting!