Applying a function on array that returns outputs with different size in a vectorized manner

点点圈 提交于 2020-01-19 13:09:38

问题


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);

回答1:


There are 2 methods to achieve it:

It is possible to set 'UniformOutput' to false. Then, the result is a cell array.

   result = arrayfun(@(x)(1:x),array,'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)

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}

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.

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.




回答2:


In addition to the answer of Andrey I want to note that it seems, that the first approach, using the option UniformOutput, is slightly faster:

>> tic; cellfun(@(x) {single(x)}, data); toc;
Elapsed time is 0.031817 seconds.

>> tic; cellfun(@(x) single(x), data,'UniformOutput',0); toc;
Elapsed time is 0.025526 seconds.


来源:https://stackoverflow.com/questions/9044712/applying-a-function-on-array-that-returns-outputs-with-different-size-in-a-vecto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!