How to replace cell values with consecutive values related to their index

1 回表示 (過去 30 日間)
Dc215905
Dc215905 2021 年 5 月 28 日
コメント済み: dpb 2021 年 5 月 29 日
For example:
a = 1x3 cell array
columns 1 through 3
{1x1} {1x5} {1x3}
I'd like to be able to replace the values in each cell array with consecutive values so that:
a = 1x3 cell array
{[1]} {[2 3 4 5 6]} {[7 8 9]}
Thanks!

採用された回答

dpb
dpb 2021 年 5 月 29 日
c=[{cell(1,1)} {cell(1,5)} {cell(1,3)}]; % original cell array
% engine
n=cellfun(@numel,c);
v=1:sum(n);
i1=1;
for i=1:numel(n)
i2=i1+n(i)-1;
c{i}=v(i1:i2);i1=i2+1;
end
results in
>> c
c =
1×3 cell array
{[1]} {1×5 double} {1×3 double}
>> c{:}
ans =
1
ans =
2 3 4 5 6
ans =
7 8 9
>>
There's probably a clever accumarray() or arrayfun() syntax to avoid the explicit loop, but nothing came to me quickly...
  1 件のコメント
Dc215905
Dc215905 2021 年 5 月 29 日
Thank you!
That's way less convoluted than what I cam up with:
b = 0;
in = 1;
for i = 1:length(CellMatrix)
c = b(end);
b = [];
for in = 1:length(CellMatrix{i})
length(CellMatrix{i});
b(end+1) = c + 1;
c = c +1;
end
in = 1;
CellMatrix(i) = {b};
end

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

その他の回答 (1 件)

Stephen23
Stephen23 2021 年 5 月 29 日
編集済み: Stephen23 2021 年 5 月 29 日
Simpler:
C = {cell(1,1),cell(1,5),cell(1,3)}
C = 1×3 cell array
{1×1 cell} {1×5 cell} {1×3 cell}
N = cellfun(@numel,C);
D = mat2cell(1:sum(N),1,N)
D = 1×3 cell array
{[1]} {[2 3 4 5 6]} {[7 8 9]}
  1 件のコメント
dpb
dpb 2021 年 5 月 29 日
That's what I intended, but kept muffing the mat2cell syntax...it's always thrown me for a loop for some reason -- rarely ever use it I guess is likely cause.

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

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by