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.

 採用された回答

Stephen23
Stephen23 2017 年 11 月 14 日
編集済み: Stephen23 2017 年 11 月 14 日

0 投票

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 件のコメント

Peter Tisdall
Peter Tisdall 2017 年 11 月 15 日
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 2017 年 11 月 15 日
編集済み: Stephen23 2017 年 11 月 15 日
@Peter Tisdall: in this case you can use vertcat instead:
D = accumarray(idx,idr(:),[],fun);
D = vertcat(D{:});
Peter Tisdall
Peter Tisdall 2017 年 11 月 15 日
Thanks again for the speedy response, this works like a charm!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Chemistry についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by