MATLAB Answers

# Creating an array by repeating the index of a cell by the length of the cell

1 view (last 30 days)
Ryan Waite on 27 Apr 2017
Answered: Stephen Cobeldick on 28 Apr 2017
I have 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]

#### 0 Comments

Sign in to comment.

### Answers (2)

John Malik on 28 Apr 2017
repelem(1:length(data), cellfun(@length, data))

#### 0 Comments

Sign in to comment.

Stephen Cobeldick on 28 Apr 2017
Without repelem:
>> data = {[1,2,3], [4,5], [6], [7,8,9,10]};
>> fun = @(c,n)n*ones(size(c{1}));
>> cell2mat(arrayfun(fun,data,1:numel(data),'uni',0))
ans =
1 1 1 2 2 3 4 4 4 4

#### 0 Comments

Sign in to comment.

### Community Treasure Hunt

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

Start Hunting!