Merging elements in cell array using common value

I have a 110x6 cell containing information about chemicals in different states, that is currently organised by state (sol/liq). I am looking to merge the elements that belong to the same chemicals, however every chemical does not have two states.
So for example, I would like to merge row 1 and 2 into one row (as they have the same value in column 2 and 3), so that I have 1x703 doubles in columns 4,5, and 6.
I have been trying to do this by adapting the method explained here: https://uk.mathworks.com/matlabcentral/answers/365490-merging-elements-into-a-single-cell-array
But I am not having much luck.
I have also been trying to achieve something similar using a structure instead of a cell with little success.

 Respuesta aceptada

Stephen23
Stephen23 el 14 de Nov. de 2017
Editada: Stephen23 el 14 de Nov. de 2017
Here is one solution using unique and accumarray:
C = {...
'Lisol',6.9410,0.0774,1,11,111;...
'Liliq',6.9410,0.0774,2,22,222;...
'Nasol', 22.99,0.2564,3,33,333;...
'Naliq', 22.99,0.2564,4,44,444;...
'Ksol',39.098,0.4361,5,55,555};
%
k = 1e4; % for a tolerance of 1e-4
M = round(k*cell2mat(C(:,2:3))); % avoid floating point errors.
[~,~,idx] = unique(M,'rows');
idr = 1:numel(idx);
fun = @(r){{C(r,1),C(r(1),2),C(r(1),3),[C{r,4}],[C{r,5}],[C{r,6}]}};
D = cell2mat(accumarray(idx,idr(:),[],fun));
And checking the first row of the output cell array:
>> D{1,:}
ans =
Lisol
Liliq
ans = 6.9410
ans = 0.077400
ans =
1 2
ans =
11 22
ans =
111 222
You can see that it kept all of the strings from the first column, kept one of each of the second and third column values, and horizontally concatenated the fourth, fifth, and sixth columns. Adjust the function to suit your needs.

3 comentarios

Thanks for the quick response! When I use this method I am getting the error:
"CELL2MAT does not support cell arrays containing cell arrays or objects."
Stephen23
Stephen23 el 15 de Nov. de 2017
Editada: Stephen23 el 15 de Nov. de 2017
@Peter Tisdall: in this case you can use vertcat instead:
D = accumarray(idx,idr(:),[],fun);
D = vertcat(D{:});
Peter Tisdall
Peter Tisdall el 15 de Nov. de 2017
Thanks again for the speedy response, this works like a charm!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Chemistry en Centro de ayuda y File Exchange.

Preguntada:

el 14 de Nov. de 2017

Comentada:

el 15 de Nov. de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by