modifying a cell array

17 visualizaciones (últimos 30 días)
shobhit mehrotra el 14 de Abr. de 2015
Respondida: Guillaume el 15 de Abr. de 2015
I have a cell array
A = cell 1: 1,2,5,6 (4x1)
cell 2: 3, 5.5, 6.4, 3, 7.2 (5x1)
cell 3: 15 (1x1)
cell 4: 2, 3.25, 6.35 (3x1)
cell 5: 2, 13,22 (3x1)
I want to combine any cell with than 3 elements to the cell following it. For example merge cell 3 into cell 4, so the "new" cell 3 consists of 2, 3.25, 6.35, 15.
Thanks
1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Guillaume el 15 de Abr. de 2015
What if you have two consecutive cells with only 1 element, should both be merged together and with the 3rd following cell?

Iniciar sesión para comentar.

Respuestas (2)

Abhishek GS el 15 de Abr. de 2015
Hi Shobit,
I am assuming you want to know how to modify/combine cell arrays and you already know how to loop through the different cell arrays that you have. This may work for you.
cell3={15} cell4={2,3.25,6.35} if (length(cell3)<3) cell4={cell4{:},cell3{:}} end
Hope this helps,
Abhishek
1 comentarioMostrar -1 comentarios más antiguosOcultar -1 comentarios más antiguos
Abhishek GS el 15 de Abr. de 2015
Sorry about the formatting. This looks better.
cell3={15}
cell4={2,3.25,6.35}
if (length(cell3)<3)
cell4={cell4{:},cell3{:}}
end

Iniciar sesión para comentar.

Guillaume el 15 de Abr. de 2015
Here is a vectorised way of doing it. This may or may not be faster than doing it explicitly with a loop:
tooshort = cellfun(@numel, A) < 3;
assert(all(diff(find(tooshort)) > 1), 'Does not work with two consecutive cells being too short')
assert(tooshort(end) == 0, 'Does not work if last element is too short');
tooshort = tooshort(1:end-1);
A([tooshort false]) = cellfun(@horzcat, A([tooshort false]), A([false tooshort]), 'UniformOutput', false); %merge consecutive cells
A([false tooshort]) = []; %and delete the 2nd cells
0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

Categorías

Más información sobre Multidimensional Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by