Add a zero element to the beginning of each existing cell array

2 views (last 30 days)
I have C={[-8;-5],[1;-4;-5;-5;-5],[-3;-5]}
I want to get this result CC={[0;-8;-5],[0;1;-4;-5;-5;-5],[0;-3;-5]}
I use this code, but do not works c = cellfun(@(x)(x(0)==0), a, 'UniformOutput', false);

Accepted Answer

Stephen23
Stephen23 on 18 Jan 2019
Edited: Stephen23 on 18 Jan 2019
cellfun(@(v)[0;v],C,'uni',0)
And checking:
>> C = {[-8;-5],[1;-4;-5;-5;-5],[-3;-5]};
>> CC = cellfun(@(v)[0;v],C,'uni',0);
>> CC{:}
ans =
0
-8
-5
ans =
0
1
-4
-5
-5
-5
ans =
0
-3
-5
  6 Comments
Stephen23
Stephen23 on 19 Jan 2019
Edited: Stephen23 on 19 Jan 2019
Lets split this line:
tmp = cellfun(@(c,i)c+B(i(1)),CC,index,'uni',0);
into two lines:
fun = @(c,i)c+B(i(1));
tmp = cellfun(fun,CC,index,'uni',0);
where the first line defines an anonymous function:
For each of the corresponding cell contents in CC and index, that anonymous function will calculate
c+B(i(1))
where c and i are the function inputs, as provided by cellfun, i.e. are the cell contents of CC and index. So this is equivalent to:
CC{1}+B(index{1}(1))
CC{2}+B(index{2}(1))
CC{3}+B(index{3}(1))
... etc.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 19 Jan 2019
Granted, cellfun() is a bit cryptic, so if you want a simple, easy to understand intuitive method, just use for loops:
C = {[-8;-5],[1;-4;-5;-5;-5],[-3;-5]};
for col = 1 : size(C, 2)
for row = 1 : size(C, 1)
existingContents = C{row, col}; % Get existing vector
C{row, col} = [0; existingContents]; % Prepend 0
end
end
celldisp(C)
Sure, it's not as compact, and slightly slower (a millsecond or so for that array) but it's more intuitive.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!