在数组上应用一个函数,该函数以矢量化方式返回不同大小的输出 [英] Applying a function on array that returns outputs with different size in a vectorized manner
问题描述
如何应用使用arrayfun
将非标量输出返回到数组的函数?
How to apply a function that returns non scalar output to arrays using arrayfun
?
例如-如何将以下代码向量化?
For example - How to vectorize the following code?
array = magic(5);
A = cell(size(array));
for i=1:5
for j=1:5
A{i,j} = 1:array(i,j);
end
end
这种天真的矢量化尝试不起作用,因为输出不是标量
This naive attempt to vectorize does not work, because the output is not a scalar
array = magic(5);
result = arrayfun(@(x)(1:x),array);
推荐答案
有2种方法可以实现:
可以将"UniformOutput"设置为false.然后,结果是一个单元格数组.
It is possible to set 'UniformOutput' to false. Then, the result is a cell array.
result = arrayfun(@(x)(1:x),array,'UniformOutput',false);
但是我今天发现了一个不错的技巧,该函数本身可以返回一个单元格.这样就无需每次都键入'UniformOutput',false
.
But there is a nice trick that I have found today, the function itself can return a cell. This removes the need of typing 'UniformOutput',false
each and every time.
result = arrayfun(@(x){1:x},array)
什么是真正有趣的,在这里我不必键入@(X)({1:x})
,但只能使用花括号@(X){1:x}
What is really interesting here that I don't have to type @(X)({1:x})
but I can define it only by using curly bracers @(X){1:x}
编辑(1):正如@Jonas正确指出的那样,毫无疑问不需要常规护腕()
,因为它们是可选的.例如,@(x) x+1
是有效的语法.
Edit(1): As @Jonas correctly points out, there is no wonder that the regular bracers ()
are not needed, as they are optional. For example, @(x) x+1
is a valid syntax.
编辑(2):使用花括号方法或UniformOutput,false
之间有很小的区别.当输入数组为空时,它们的行为是不同的.
Edit(2): There is a small difference between using the curly bracers method or the UniformOutput,false
. When the input array is empty, their behavior is different.
这篇关于在数组上应用一个函数,该函数以矢量化方式返回不同大小的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!