如何在interp2中使用ndgrid

huangapple go评论56阅读模式
英文:

How to use ndgrid with interp2

问题

Matlab中有两个用于创建网格数据的函数,ndgridmeshgridmeshgrid非常让人讨厌,因为它混淆了行和列,而ndgrid保持了一致性。所以我喜欢使用ndgrid

但事实证明,为了使用interp2进行插值,我需要像meshgrid一样的网格数据格式。但我的其余代码无法处理meshgrid的格式,我想继续使用ndgrid。如何让ndgridinterp2配合工作,以及这种混乱的方法是什么?我厌倦了随机转置矩阵,直到代码能够运行。

[X, Y] = ndgrid(0:0.1:1, 0:0.1:2);
F = cos(X) .* sin(Y);
[X2, Y2] = ndgrid(0:0.05:1, 0:0.05:2);
F2 = interp2(X, Y, F, X2, Y2);

我知道有一种方法可以通过转置一堆东西来使它工作,什么是正确的方法?当ndgridmeshgrid在行和列之间翻转时,这真是令人困惑,肯定有一个"正确的方法"来解决这个问题。在过去的六年中,我因为ndgridmeshgrid混淆了行和列而感到非常沮丧。

英文:

Matlab infamously has two functions for creating gridded data, ndgrid and meshgrid. meshgrid is very annoying because it mixes up rows and columns whereas ndgrid keeps it consistent. So I like to stick with ndgrid.

But it turns out, in order to interpolate using interp2, I need meshgrid style gridded data. But the rest of my code cannot handle if I used meshgrid, I want to stick to ndgrid. How do I make ndgrid work with interp2, and what is the method to this madness? I am sick of randomly transposing matrices until the code works.

[X, Y]=ndgrid(0:0.1:1,0:0.1:2);
F=cos(X).*sin(Y);
[X2, Y2]=ndgrid(0:0.05:1,0:0.05:2);
F2=interp2(X,Y,F,X2,Y2);

I know there is a way to get this to work by transposing bunch of stuff, what is the right way to do this? It is so immensely confusing when ndgrid and meshgrid are flipping rows and columns around, there has to be a "right way" to navigate this. Over the course of past six years, I have been brought to tears by the frustration caused by ndgrid and meshgrid flipping around rows and columns.

答案1

得分: 2

尝试使用griddedInterpolant,它做出类似ndgrid的假设。对于你的示例:

[X, Y] = ndgrid(0:0.1:1, 0:0.1:2);
Z = cos(X) .* sin(Y);
F = griddedInterpolant(X, Y, Z);
[X2, Y2] = ndgrid(0:0.05:1, 0:0.05:2);
Z2 = F(X2, Y2);

如果你需要在类似你的示例的2-D情况中使用interp2,那么只需知道[X, Y] = ndgrid(x, y) 等同于 [Y, X] = meshgrid(y, x)。所以对于你的示例,你可以这样做:

[X, Y] = ndgrid(0:0.1:1, 0:0.1:2);
F = cos(X) .* sin(Y);
[X2, Y2] = ndgrid(0:0.05:1, 0:0.05:2);
F2 = interp2(Y, X, F, Y2, X2);

最后,这是从meshgrid 转换到 ndgrid 在3-D中的通用方法

英文:

Try griddedIntepolant, which makes ndgrid-like assumptions. For your example:

[X, Y]=ndgrid(0:0.1:1,0:0.1:2);
Z=cos(X).*sin(Y);
F=griddedInterpolant(X, Y, Z);
[X2, Y2]=ndgrid(0:0.05:1,0:0.05:2);
Z2=F(X2,Y2);

If you need to use interp2 for 2-D cases like your example, then it suffices to know that [X, Y]=ndgrid(x,y) is equivalent to [Y, X]=meshgrid(y,x). So for your example, you could do:

[X, Y]=ndgrid(0:0.1:1,0:0.1:2);
F=cos(X).*sin(Y);
[X2, Y2]=ndgrid(0:0.05:1,0:0.05:2);
F2=interp2(Y,X,F,Y2,X2);

Lastly, this is supposedly the general method to covert from meshgrid to ndgrid in 3-D.

huangapple
  • 本文由 发表于 2023年2月16日 04:55:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465349.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定