Search code examples
pythonmatlabiterable-unpacking

How to translate python tuple unpacking to Matlab?


I am translating some python code to Matlab, and want to figure out what the best way to translate the python tuple unpacking to Matlab is.

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

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 is translated 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 is

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 the python code in Matlab?


Solution

  • Without knowing what Body is, this is my solution:

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

    or, if the output has to encapsulated in a cell array:

    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)