views:

263

answers:

2

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?

+2  A: 

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)
Amro
When I actually implement Body in a seperate class file (see above), I get the following error:??? Error using ==> cellfunBody type is not currently implemented.Error in ==> driver at 9bodies = cellfun(@(tuple)Body(tuple{1},tuple{2}), coords);
celil
try the second form with: `UniformOutput=false` to construct a cell array instead
Amro
@Dzhelil: The error you're getting seems like it's related to the `Body` class you've created. Have you checked that it is working correctly? Try this: `testBody = Body(X1,Y1)`.
gnovice
Using `UniformOutput=false` as per Amro's suggestion solved the problem.
celil
A: 

It appears that Amro's answer will work for you. However, if you don't really need or want to create a new Body class, there's a straight-forward way to construct an array of structures using the STRUCT command:

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});

In this case, each element of the array bodies is a structure as opposed to a class object, but you should be able to use it in much the same way.

gnovice