How to translate python unpack tuple in matlab?

I have been translating Python code into Matlab and I want to find out what is the best way to translate the python package for unpacking in Matlab.

For the purposes of this example, a Bodyis a class whose constructor takes two functionals as input.

I have the following python code:

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]

which translates to the following matlab code

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

where body

classdef Body < handle

    properties
        X,Y
    end

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

end

Is there a better and more elegant way to express the last line of python code in Matlab?

+3
source share
2 answers

Not knowing what it is Body, this is my solution:

bodies = cellfun(@(tuple)Body(tuple{1},tuple{2}), coords);

or, if the output should be encapsulated in an array of cells:

bodies = cellfun(@(tuple)Body(tuple{1},tuple{2}), coords, 'UniformOutput',false);

And just for testing, I tried it with the following:

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)
+2

, Amro answer . , Body, , 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 , , .

0

Source: https://habr.com/ru/post/1722948/


All Articles