0

I am using Matlab to create a cell array of data shown below. I would like to create a new array (output) where the index of the cell is repeated "x" times. Where "x" is equal to the length of that specific cell. I can do this with for loops, but can it be done with a simple function?

data = {[1,2,3], [4,5], [6], [7,8,9,10]}
% output = [1,1,1,2,2,3,4,4,4,4]

2 Answers2

2

You can do it using cellfun and repelem

output = repelem(1:numel(data), cellfun(@numel, data));

but note that:

  • cellfun is more or less the same as a loop;
  • repelem was introduced in version R2015a.
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • 1
    [Related post](http://stackoverflow.com/questions/1975772/repeat-copies-of-array-elements-run-length-decoding-in-matlab) if `repelem` is not available – Sardar Usama Apr 27 '17 at 16:20
1

IMO @LuisMendo answer is elegant and I would go with it, but if you don't have repelem, an alternative is to use cellfun and then cell2mat:

data = {[1,2,3], [4,5], [6], [7,8,9,10]}
% output = [1,1,1,2,2,3,4,4,4,4]
output = cell2mat(cellfun(@(d,i) i*ones(1,numel(d)),data,...
    num2cell(1:numel(data)),'UniformOutput',0) )
user2999345
  • 4,195
  • 1
  • 13
  • 20
  • 1
    Good idea. Or, perhaps simpler, `cell2mat(arrayfun(@(k) repmat(k,1,numel(data{k})), 1:numel(data), 'UniformOutput', false))` – Luis Mendo Apr 27 '17 at 16:22
  • repelem is exactly what I was looking for, but unfortunately I'm on R2012a. This solution works great though, thanks! – Ryan Waite Apr 27 '17 at 16:50
  • @RyanWaite Consider accepting it in that case. There's a tick mark on the upper left. And welcome to Stack Overflow! – Luis Mendo Apr 27 '17 at 19:18