gpt4 book ai didi

python - 如何将 python 元组解包转换为 Matlab?

转载 作者:行者123 更新时间:2023-11-28 17:54:58 25 4
gpt4 key购买 nike

我正在将一些 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

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

最佳答案

不知道 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)

关于python - 如何将 python 元组解包转换为 Matlab?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1739566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com