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 o开发者_运维技巧f the python code in Matlab?
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)
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.
精彩评论