Why does gradient function calculate wrong dimensions 1 and 2?
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Michael Mauersberger
el 30 de Abr. de 2020
Hi there,
I want to calculate multidimensional gradient of a scalar field. After I got to know the difference between meshgrid and ndgrid (general n-dimensional), I noticed that gradient calculates inconsistently when using with ndgrid.
While meshgrid assumes first dimension as y and second dimension as x, ndgrid does it the other way around (x first, y second). The gradient function does it the same way as meshgrid. Obviously, gradient and meshgrid belong together somehow.
But what should I do to calculate gradients consistently with n dimensions?
Example:
[mshx,mshy,mshz] = ndgrid(0:.1:10,0:.1:10,0:.1:10);
[gxx,gyx,gzx] = gradient(mshx);
[gxy,gyy,gzy] = gradient(mshy);
[gxz,gyz,gzz] = gradient(mshz);
Here all gij are zero except gyx, gxy and gzz.
Is there an elegant way to do that kind of calculus to finally get all gij equal zero except for gxx, gyy, gzz?
Thank you for your help.
Best regards
Michael
0 comentarios
Respuesta aceptada
Stephen23
el 30 de Abr. de 2020
Editada: Stephen23
el 30 de Abr. de 2020
>> mygrad = @(m)gradient(permute(m,[2,1,3:ndims(m)]));
>> [gxx,gyx,gzx] = mygrad(mshx);
>> [gxy,gyy,gzy] = mygrad(mshy);
>> [gxz,gyz,gzz] = mygrad(mshz);
Note that this works correctly for all N, even the edge-case when N==1, i.e. a vector input:
mshx = ndgrid(0:.1:10);
Or you could just copy gradient Mfile to your working directory, save it with a different function name (e.g. mygrad), and remove the code that permutes the first two dimensions. It wouldn't be very hard.
"Why does gradient function calculate wrong dimensions 1 and 2?"
Because many users think of array horizontal dimension as x, and array vertical dimension as y... but these are the second and first dimensions respectively (of standard matrix/array size notation). This is probably best illustrated in the meshgrid help.
The gradient documentation does state: "The first output FX is always the gradient along the 2nd dimension of F, going across columns. The second output FY is always the gradient along the 1st dimension of F, going across rows. For the third output FZ and the outputs that follow, the Nth output is the gradient along the Nth dimension of F."
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Filter Design en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!