3

我正在将一些 python 代码翻译成 Matlab,并想弄清楚将 python 元组解包翻译成 Matlab 的最佳方法是什么。

就本示例而言,aBody是一个类,其构造函数将两个函数作为输入。

我有以下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

身体在哪里

classdef Body < handle

    properties
        X,Y
    end

    methods
        function self = Body(X,Y)
            self.X = X;
            self.Y = Y;
        end
    end

end

有没有更好更优雅的方式来表达matlab中python代码的最后一行?

4

2 回答 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)
于 2009-11-16T02:06:21.473 回答
0

看来Amro 的答案对你有用。但是,如果您真的不需要或不想创建一个新类,有一种直接的方法可以使用STRUCT命令Body构造一个结构数组:

X1 = @(t) cos(t);
Y1 = @(t) sin(t);
X2 = @(t) cos(t) + 1;
Y2 = @(t) sin(t) + 1;
bodies = struct('X',{X1 X2},'Y',{Y1 Y2});

在这种情况下,数组的每个元素bodies都是一个结构,而不是类对象,但您应该能够以几乎相同的方式使用它。

于 2009-11-16T03:52:08.087 回答