Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
回复
 
主题工具 显示模式
旧 2019-12-10, 16:49   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 如何将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 身体在哪里

classdef Body < handle properties X,Y end methods function self = Body(X,Y) self.X = X; self.Y = Y; end end end 有没有更好,更优雅的方法来表达Matlab中python代码的最后一行?


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

更多&回答...
poster 当前离线   回复时引用此帖
回复


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 22:16


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.