merging elements into a single cell array

6 visualizaciones (últimos 30 días)
Satarupa Khamaru
Satarupa Khamaru el 6 de Nov. de 2017
Comentada: Satarupa Khamaru el 7 de Nov. de 2017
I have a 366x1 cell array named B. i would like to copy each row into another cell array like 2nd and 3rd value of 1st row will be merged with 2nd and 3rd value of 2nd row into a new cell array (as both index is 8). Similarly 2nd and 3rd value of 3rd row will be merged with 2nd and 3rd value of 4th row into a new cell of the same cell array (as both index is 17) and so on.
  3 comentarios
Satarupa Khamaru
Satarupa Khamaru el 6 de Nov. de 2017
Hi James,thanks a lot for your quick assistance. Yes, all rows have exactly three elements.
Image Analyst
Image Analyst el 6 de Nov. de 2017
Can you save B to a .mat file and upload it so we can try to work with it?

Iniciar sesión para comentar.

Respuestas (1)

James Tursa
James Tursa el 6 de Nov. de 2017
Does this do what you want?
C = cellfun(@(c)c(2:end),B,'uni',false);
v = cellfun(@(x)x(1),B);
u = unique(v);
result = arrayfun(@(x)[u(x),C{v==u(x)}],1:numel(u),'uni',false)';
  5 comentarios
James Tursa
James Tursa el 7 de Nov. de 2017
arrayfun( ) operates on each element of an array. In this case, it is the array formed by 1:numel(u). For each of these values 1, 2, 3, ..., numel(u), an output is generated by the first argument:
@(x)M(v==u(x),2:end)
This is a function handle, which picks off the rows of M that match u(x) and the 2nd through last columns of these rows. So in your example above, the 8 in the first column appears in the first two rows. So this function handle, when evaluated with a 1 input, generates this result:
M(v==u(1),2:end)
Since u(1) is 8, this is equivalent to:
M(v==8,2:end)
I.e., this picks off the rows of M where the first column contains an 8. The 2:end picks off all of the columns except the first column.
For the next element of the result, a value of 2 is used as input to the function handle, so you get this:
M(v==u(2),2:end)
which gives this
M(v==17,2:end)
Etc.
Finally, the ...,'uni',false,... stuff is simply to tell arrayfun( ) to put the results into a cell array.
Satarupa Khamaru
Satarupa Khamaru el 7 de Nov. de 2017
Thanks again for such a detail explanation, it helps a lot. thanks

Iniciar sesión para comentar.

Categorías

Más información sobre Creating and Concatenating Matrices 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