파이썬 튜플 풀기를 MATLAB로 번역하는 방법은 무엇입니까?
-
20-09-2019 - |
문제
Python 코드를 Matlab으로 번역하고 있으며 Python Tuple을 포장 풀기를 Matlab으로 변환하는 가장 좋은 방법을 알아 내고 싶습니다.
이 예의 목적 상, a Body
생성자가 두 기능을 입력하는 클래스입니다.
다음 파이썬 코드가 있습니다.
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)
제휴하지 않습니다 StackOverflow