我知道做到这一点的唯一方法是使用deal
。但是,这仅适用于元胞数组,或显式参数deal
。因此,如果你想处理矩阵/向量,你必须首先转换为元胞数组num2cell
/mat2cell
. E.g.:
% 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{:})
).
如果你真的想减少行数,有一个解决方案这个问题 https://stackoverflow.com/questions/2337126/how-do-i-do-multiple-assignment-in-matlab您只需创建自己的函数即可执行此操作,在此处重复并进行修改,以便您可以定义要分割的轴:
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
但它仍然执行矩阵 -> 单元 -> 矩阵的操作。如果你的向量很小并且你没有在循环中执行一百万次,那么你应该没问题。