I need help on creating a cell array in MATLAB where each cell is an array of different sizes. For example, let's assume I have this simple array and the value:
A = [5 3 8 7 0 4 1];
B = 10;
The cell array C
must be created such that:
C =
[10 20 30 40 50]
[10 20 30]
[10 20 30 40 50 60 70 80]
[10 20 30 40 50 60 70]
[Empty matrix 1x0]
[10 20 30 40]
[10]
Is it possible to do that in one operation only? I have tried:
C = cellfun(@(a,b)b*ones(1,a), A,B)
but it did not work.
cellfun
expects a cell array as the input into the function. You have a numeric array so usearrayfun
instead. You are also not outputting a scalar per element in the array so you need to set theUniformOutput
flag to 0. Finally, use thecolon
operator to do what you need instead of matrix multiplication. The output will unfortunately be a row vector of cells so if you absolutely need a column vector such as what you have shown in your post, transpose the output:Take note that the anonymous function declared as the first input into
arrayfun
has lexical scope, meaning that any variables that were visible in the workspace before the anonymous function declaration is visible. You can just access that variable inside your function instead of having to manually feed it intoarrayfun
as a separate input.We now get: