-1

Repeating data in a cell structure in matlab / octave

Greetings All

I have a MATLAB cell structure like this below:

original_array={
File1.wav
File2.wav
File3.wav
}

And I want to repeat or adjust or duplicate the data in the cell structure. I was thinking of using for loops for each item in the cell structure and then create another cell structure array but that just seems like overkill. Another idea that came to mind was to have

1) an array contain what cell I wanted to repeat 2)and the amount of times I want a cell in a cell structure to be repeated. 3)and create a new cell structure from the array.

The new repeated cell structure array would get data from the *original_array* (structure array) and a new cell structure array would be created based on the *rep_cells* array

Example. rep_cells =[1,3;2,1;3,4] %this would be used to select what cells in the orginal_array to repeat and how many times to repeat them

new_cells={
File1.wav
File1.wav
File1.wav
File2.wav
File3.wav
File3.wav
File3.wav
File3.wav
}

Any idea the best way to do this.

Thanks

Rick T
  • 3,349
  • 10
  • 54
  • 119

2 Answers2

2

you can use repmat to replicate cell elements. For example:

a={'File1.wav', 'File2.wav','File3.wav'}

repmat(a,[2 2])

ans = 
    'File1.wav'    'File2.wav'    'File3.wav'    'File1.wav'    'File2.wav'    'File3.wav'
    'File1.wav'    'File2.wav'    'File3.wav'    'File1.wav'    'File2.wav'    'File3.wav'

Here's the matlab / octave test code I used with repmat encase someone needs it in the future

%test repmat
a={'File1.wav'; 'File2.wav';'File3.wav'}
b={};
repval_array=[1,3;2,1;3,4];
for ii=1:1:length(repval_array)
    b_tmp=repmat(a(repval_array(ii,1),1),[1 repval_array(ii,2)])
    b=[b,b_tmp]
end

Answer

b = 
{
  [1,1] = File1.wav
  [1,2] = File1.wav
  [1,3] = File1.wav
  [1,4] = File2.wav
  [1,5] = File3.wav
  [1,6] = File3.wav
  [1,7] = File3.wav
  [1,8] = File3.wav
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
bla
  • 25,846
  • 10
  • 70
  • 101
  • First: Nice, I didnt know about this function. Second: I just looked it up in the docs-> you can use it not only for cell-arrays, other types of array - e.g. numerical matrices - can be replicated as well. [doc: repmat](http://www.mathworks.de/de/help/matlab/ref/repmat.html) – Lucius II. Jul 25 '13 at 07:10
  • I didn't say that repmat can be used ONLY to replicate cell elements. just from its name it REPlicates MATrices... see for example my answer to this question ... http://stackoverflow.com/questions/14532457/a-matrix-operation-in-matlab/14532565#14532565 – bla Jul 25 '13 at 07:13
0

Looks a bit cryptic but you can use this

original_array(cell2mat(arrayfun(@(x,y) x*ones(y,1), rep_cells(:,1), rep_cells(:,2), 'UniformOutput', false)))
Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52