How to replace cell values with consecutive values related to their index
    3 次查看(过去 30 天)
  
       显示 更早的评论
    
采纳的回答
  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 个)
  Stephen23
      
      
 2021-5-29
        
      编辑:Stephen23
      
      
 2021-5-29
  
      Simpler:
C = {cell(1,1),cell(1,5),cell(1,3)}
N = cellfun(@numel,C);
D = mat2cell(1:sum(N),1,N)
1 个评论
  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 Exchange 中查找有关 Matrix Indexing 的更多信息
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


