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);
댓글 수: 0
채택된 답변
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
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
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!