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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…