How do I do multiple assignment in MATLAB?

2019-01-01 07:15发布

Here's an example of what I'm looking for:

>> foo = [88, 12];
>> [x, y] = foo;

I'd expect something like this afterwards:

>> x

x =

    88

>> y

y =

    12

But instead I get errors like:

??? Too many output arguments.

I thought deal() might do it, but it seems to only work on cells.

>> [x, y] = deal(foo{:});
??? Cell contents reference from a non-cell array object.

How do I solve my problem? Must I constantly index by 1 and 2 if I want to deal with them separately?

9条回答
只靠听说
2楼-- · 2019-01-01 08:00

You don't need deal at all (edit: for Matlab 7.0 or later) and, for your example, you don't need mat2cell; you can use num2cell with no other arguments::

foo = [88, 12];
fooCell = num2cell(foo);
[x y]=fooCell{:}

x =

    88


y =

    12

If you want to use deal for some other reason, you can:

foo = [88, 12];
fooCell = num2cell(foo);
[x y]=deal(fooCell{:})

x =

    88


y =

    12
查看更多
有味是清欢
3楼-- · 2019-01-01 08:01

Create a function arr2vars for convenience

function varargout = arr2vars(arr)
% Distribute elements over variables

N = numel(arr);
if nargout ~= N
    error('Number of outputs does not match number of elements')
end
for k = 1:N
    varargout{k} = arr(k);
end

You can use it then like this

[~,roi] = imcrop(im);
[x,w,y,h] = arr2vars(roi);
查看更多
大哥的爱人
4楼-- · 2019-01-01 08:01

There is an easier way.

x = foo (1, 1)  
y = foo (1, 2)

Provides

>> x

x =

88

>> y

y =

12

Full documentation at Mathworks.

查看更多
登录 后发表回答