Using a function in an array that returns vectors with different sizes

How to apply a function that returns non-scalar output to arrays with 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 at vectorization does not work because the output is not a scalar

array = magic(5);
result = arrayfun(@(x)(1:x),array);
+2
source share
2 answers

There are two ways to achieve it:

You can set 'UniformOutput' to false. Then the result is an array of cells.

   result = arrayfun(@(x)(1:x),array,'UniformOutput',false);

But there is a good trick I found today, the function itself can return the cell. This eliminates the need to type 'UniformOutput',falseeach time.

    result = arrayfun(@(x){1:x},array)

, @(X)({1:x}), @(X){1:x}

(1): @Jonas, , () , . , @(x) x+1 .

(2): UniformOutput,false. , .

+6

, , , UniformOutput, :

>> 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.
+1

All Articles