我知道这样做的唯一方法是使用deal。但是,这仅适用于单元格数组,或者适用于deal中的显式参数。因此,如果要处理矩阵/向量,则必须首先使用num2cell / mat2cell转换为单元格数组。例如。:
% multiple inputs
[a b] = deal(42,43) % a=2, b=3
[x y z] = deal( zeros(10,1), zeros(10,1), zeros(10,1) )
% vector input
li = [42 43];
lic = num2cell(li);
[a b]=deal(lic{:}) % unforunately can't do num2cell(li){:}
% a=42, b=43
% matrix input
positions = zeros(10,3);
% create cell array, one column each
positionsc = mat2cell(positions,10,[1 1 1]);
[x y z] = deal(positionsc{:})第一种形式很好(deal(x,y,...)),因为它不需要你明确地制作单元格数组。
否则我认为当你必须将矩阵转换为单元阵列而不是再次转换它们时,不值得使用deal:只需节省开销。在任何情况下,它仍然需要3行:首先定义矩阵(例如li),然后转换为单元格(lic),然后执行deal(deal(lic{:}))。
如果你真的想减少行数,可以在this question中找到一个解决方案,在这里您可以自己创建函数,在此处重复,并进行修改,以便您可以定义要拆分的轴:
function varargout = split(x,axis)
% return matrix elements as separate output arguments
% optionally can specify an axis to split along (1-based).
% example: [a1,a2,a3,a4] = split(1:4)
% example: [x,y,z] = split(zeros(10,3),2)
if nargin < 2
axis = 2; % split along cols by default
end
dims=num2cell(size(x));
dims{axis}=ones([1 dims{axis}]);
varargout = mat2cell(x,dims{:});
end然后像这样使用:
[a b] = split([41 42])
[x y z]= split(zeros(10,3), 2) % each is a 10x1 vector
[d e] = split(zeros(2,5), 1) % each is a 1x5 vector它仍然做矩阵 - >单元 - >矩阵的事情。如果你的向量很小而且你没有在一个循环内做一百万次你应该没问题。