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

2 次查看(过去 30 天)
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);

采纳的回答

Stephen23
Stephen23 2019-1-18
编辑:Stephen23 2019-1-18
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 个评论
Stephen23
Stephen23 2019-1-19
编辑:Stephen23 2019-1-19
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.

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
Image Analyst 2019-1-19
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.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by