在 matlab 中表示向量值函数
将以下简短的 python/numpy 代码转换为 matlab 的最佳方法是什么
from numpy import *
F = lambda x, y: (-y, x)
points = array(meshgrid([1,2,3], [4,5,6,7]))
vx, vy = F(*points)
print vx, vy
在上面的代码中,F
旨在表示向量值速度场。具体来说,向量值函数应该使用单元格来表示,还是有更好的方法来实现?
第一次尝试翻译上面的代码:
F = @(x,y) {-y, x};
[X, Y] = meshgrid(1:3, 4:7);
rslt = F(X, Y);
[vx, vy] = rslt{:};
有更优雅的方法吗?例如,匿名函数是否可以返回多个值,以便可以像这样 [vx, vy] = F(X,Y);
那样调用它,而不必定义一个中间 rslt
变量?
What is the best way to translate the following brief python/numpy code to matlab
from numpy import *
F = lambda x, y: (-y, x)
points = array(meshgrid([1,2,3], [4,5,6,7]))
vx, vy = F(*points)
print vx, vy
In the code above, F
is intended to represent a vector-valued velocity field. Specfically, should a vector-valued function be represented using cells, or is there a better way to do it?
A first attempt to translate the above code:
F = @(x,y) {-y, x};
[X, Y] = meshgrid(1:3, 4:7);
rslt = F(X, Y);
[vx, vy] = rslt{:};
Is there a more elegant way to do it? For example, could the anonymous function return more than one value so that one can call it like this [vx, vy] = F(X,Y);
rather than having to define an intermediate rslt
variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将其分为两个函数:
You could split it into two functions:
内联函数不能返回多个输出,这似乎很奇怪。有几种可能的解决方法:
如果向量是 2D,您始终可以将它们打包为复数。
您可以只对结果建立索引。例如
v = f(x,y)
并使用v(1)
和v(2)
使用
deal< /代码>如下:
返回:
a=-2
和b=1
在我看来,第二个选项是最干净的(或者您可以只声明一个
function
而不是使用内联函数。MATLAB现在支持函数内的函数,类似于 python)。It does seem strange that inline functions cannot return more than one output. Several workarounds are possible:
If the vectors are 2D, you can always pack them as a complex number.
You can just index the result. E.g.
v = f(x,y)
and usev(1)
andv(2)
Use
deal
as follows:Returns:
a=-2
andb=1
The 2nd option is the cleanest, in my opinion (Or you can just declare a
function
instead of using an inline function. MATLAB now supports functions within functions, similar to python).