Why does gradient function calculate wrong dimensions 1 and 2?
9 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Stephen23
2020-4-30
编辑:Stephen23
2020-4-30
>> 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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Filter Design 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!