如何将Python的元组解包转换为Matlab?
我正在把一些Python代码转换成Matlab,想找出将Python中的元组解包转换到Matlab的最佳方法。
在这个例子中,Body
是一个类,它的构造函数需要两个函数作为输入。
我有以下的Python代码:
X1 = lambda t: cos(t)
Y1 = lambda t: sin(t)
X2 = lambda t: cos(t) + 1
Y2 = lambda t: sin(t) + 1
coords = ((X1,Y1), (X2,Y2))
bodies = [Body(X,Y) for X,Y in coords]
这段代码被转换成了以下的Matlab代码:
X1 = @(t) cos(t)
Y1 = @(t) sin(t)
X2 = @(t) cos(t) + 1
Y2 = @(t) sin(t) + 1
coords = {{X1,Y1}, {X2,Y2}}
bodies = {}
for coord = coords,
[X,Y] = deal(coord{1}{:});
bodies{end+1} = Body(X,Y);
end
其中Body是:
classdef Body < handle
properties
X,Y
end
methods
function self = Body(X,Y)
self.X = X;
self.Y = Y;
end
end
end
有没有更好、更优雅的方法来在Matlab中表达Python代码的最后一行?
2 个回答
2
在不知道Body
是什么的情况下,这是我的解决方案:
bodies = cellfun(@(tuple)Body(tuple{1},tuple{2}), coords);
或者,如果输出需要放在一个单元格数组里:
bodies = cellfun(@(tuple)Body(tuple{1},tuple{2}), coords, 'UniformOutput',false);
为了测试,我用以下内容试了一下:
X1 = @(t) cos(t);
Y1 = @(t) sin(t);
X2 = @(t) cos(t) + 1;
Y2 = @(t) sin(t) + 1;
coords = {{X1,Y1}, {X2,Y2}};
%# function that returns a struct (like a constructor)
Body = @(X,Y) struct('x',X, 'y',Y);
%# tuples unpacking
bodies = cellfun(@(tuple)Body(tuple{1},tuple{2}), coords);
%# bodies is an array of structs
bodies(1)
bodies(2)