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

2 ビュー (過去 30 日間)
NA
NA 2019 年 1 月 18 日
回答済み: Image Analyst 2019 年 1 月 19 日
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.
NA
NA 2019 年 1 月 19 日
Thank you so much.

サインインしてコメントする。

その他の回答 (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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by