Ben*_*kes 44 arrays variables matlab variable-assignment
这是我正在寻找的一个例子:
>> foo = [88, 12];
>> [x, y] = foo;
Run Code Online (Sandbox Code Playgroud)
之后我会期待这样的事情:
>> x
x =
88
>> y
y =
12
Run Code Online (Sandbox Code Playgroud)
但相反,我得到的错误如下:
??? Too many output arguments.
Run Code Online (Sandbox Code Playgroud)
我想deal()
可能会这样做,但它似乎只适用于细胞.
>> [x, y] = deal(foo{:});
??? Cell contents reference from a non-cell array object.
Run Code Online (Sandbox Code Playgroud)
我该如何解决我的问题?如果我想单独处理它们,我必须经常索引1和2吗?
Ram*_*nka 43
根本不需要deal
(编辑:对于Matlab 7.0或更高版本),对于您的示例,您不需要mat2cell
; 你可以使用num2cell
没有其他参数::
foo = [88, 12];
fooCell = num2cell(foo);
[x y]=fooCell{:}
x =
88
y =
12
Run Code Online (Sandbox Code Playgroud)
如果您想deal
出于其他原因使用,您可以:
foo = [88, 12];
fooCell = num2cell(foo);
[x y]=deal(fooCell{:})
x =
88
y =
12
Run Code Online (Sandbox Code Playgroud)
小智 17
请注意,deal
接受"list"作为参数,而不是单元格数组.所以以下工作如预期:
> [x,y] = deal(88,12)
x = 88
y = 12
Run Code Online (Sandbox Code Playgroud)
语法c{:}
转换列表中的单元格数组,列表是逗号分隔值,如函数参数.这意味着您可以将c{:}
语法用作其他函数的参数deal
.要查看,请尝试以下操作:
> z = plus(1,2)
z = 3
> c = {1,2};
> z = plus(c{:});
z = 3
Run Code Online (Sandbox Code Playgroud)
小智 8
要num2cell
在一行中使用该解决方案,请定义辅助函数list
:
function varargout = list(x)
% return matrix elements as separate output arguments
% example: [a1,a2,a3,a4] = list(1:4)
varargout = num2cell(x);
end
Run Code Online (Sandbox Code Playgroud)