質問

私はMatlabのにはいくつかのPythonコードを変換し、Matlabのに開梱Pythonのタプルを変換するための最良の方法であるかを把握したいのです。

この例の目的のために、Bodyは、そのコンストラクタ入力ように、2つの汎関数をとるクラスである。

私は、次の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)

他のヒント

これは、そのアムロの答えを表示されますあなたのために動作します。本当に必要か、新しいBodyクラスを作成したくない場合は、<のhref = "http://www.mathworks.com/access/helpdeskを使用して構造体の配列を構築するストレートな方法があります/help/techdoc/ref/struct.html」のrel = "nofollowをnoreferrer"> STRUCT のコマンドます:

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の各要素は、構造ですが、ほぼ同じ方法でそれを使用することができる必要があります。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top