Matlab多变量赋值

时间:2014-09-18 07:36:05

标签: matlab

我想将长度为2的向量中的值分配给多个变量。 size()的输出能够做到这一点:

% works
[m,n] = size([0 0]);

然而,将其分为两行不起作用:

sz = size([0 0]);
[m,n] = sz;
% returns:
%   ??? Too many output arguments.

将大小分配给变量时丢失的大小的返回值有什么特别之处?

6 个答案:

答案 0 :(得分:4)

Matlab的输出参数很有意思。根据“用户”要求的数量,函数可以具有可变数量的输出。

写作时

[m,n] = size([0 0]);

您正在请求两个输出参数。在函数本身内部,这将对应于等于nargout的变量2

但是当你写作

sz = size([0 0]);

size函数识别出它是单个输出参数,并将mn作为向量而不是两个单例输出。 这种行为方式(我认为)在Matlab中通常不常见。

另请注意,Matlab不允许多个参数来分解向量:

x = [1 1]
[y,z] = x

返回Too many output arguments.

答案 1 :(得分:3)

您介绍的自定义函数非常过分,并使用eval等函数,这些函数被认为是不好的做法。它可以做得更短。这就是你所需要的:

function [ varargout ] = split( Vector )

varargout = num2cell( Vector );

end

由于varargout你有一个可变长度输出参数列表,你不需要编辑你的函数以获得更多的参数。

它适用于矢量和矩阵:

[a,b,c,d] = split( [1,2;3,4] )

a =  1

b =  3

c =  2

d =  4

如果您不喜欢矩阵兼容性,请包含条件并检查输入向量的尺寸。

答案 2 :(得分:3)

如果由于某种原因不希望在单独的函数中使用它,则可以使用匿名函数返回多个输出,如下所示:

split = @(x) deal(x(1), x(2))
A = zeros(5,3)
sz = size(A)

[x, y] = split(sz)
   x =  5
   y =  3

deal函数看到两个左侧参数,从而产生正确的输出。请注意,此功能不会很好地响应错误的输入和输出。查看Loren's blog了解详情。

答案 3 :(得分:2)

您可以将sz转换为单元格数组,然后从该数组生成comma-separated list

sz_cell = mat2cell(sz(:), ones(numel(sz),1));
[m, n] = sz_cell{:}; %// Or [m, n] = deal(sz_cell{:});

答案 4 :(得分:0)

大小值并不是特别的。它只是将sz作为单个参数处理,因为你正在复制它的大小结果,这就是为什么它不能有2个输出。

通过使用由1输出定义的任何其他函数,您将得到相同的错误,例如:[m,n] = cos(0)等。

答案 5 :(得分:0)

我找到了一种方法来做到这一点。感谢Will Robertson的回答,我意识到写一个函数是真正得到我想要的唯一方法。这是分开的。

function [ o1, o2, o3, o4, o5, o6, o7, o8 ] = split( v )
%SPLIT Splits a vector of bounded length into individual return variables.
% Split() can handle arbitrarily long input vectors, but only a fixed
% number of output variables.  @benathon
%
% Usage:
%  vec = [1 2 3 4 5];
%  [a,b,c,d,e] = split(vec);
%  [f,g]       = split(vec);

% If you would like to upgrade split() to handle more output variables,
% simply add more output variables to the function definition and
% then change this variable
maxout = 8;

[~,n] = size(v);

if n < nargout
    error('input vector too short for number of output arguments');
end

% we only need to assign this many output variables
iterations = min(n,nargout);


% Matlab catches "Too many output arguments." before we can
%if( iterations > maxout )
%    error('Too many output, edit split.m to easily upgrade');
%end


i = 1;
while i <= iterations
    expression = sprintf('o%d=v(%d);', i, i);
    eval(expression);
    i = i + 1;
end

查看评论中的用法。我还提出了一个要点:https://gist.github.com/esromneb/652fed46ae328b17e104

相关问题