merging elements into a single cell array

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 个评论

Do all of the rows always have exactly three elements?
Hi James,thanks a lot for your quick assistance. Yes, all rows have exactly three elements.
Can you save B to a .mat file and upload it so we can try to work with it?

请先登录,再进行评论。

回答(1 个)

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 个评论

the above code is not giving the desired result. Here I have uploaded B as a .mat file and also I uploaded result as .mat file, this is the format I want exactly. Here in stead of [2,24;595,67], the value should be 1st row of cell B and 2nd row of cell B together separated by semicolon i.e. [-0.7904,0.9728;1.463,0.8094].
What about this?
M = cell2mat(B);
v = M(:,1);
u = unique(v);
result = arrayfun(@(x)M(v==u(x),2:end),1:numel(u),'uni',false);
Thank you very much James. This is exactly what I was looking for and was breaking my head since long time. I am very new to matlab. Your quick assistance with this is much appreciated. Would you mind explaining the 'arrayfun' syntax? it would be a great help for me. thanks
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.
Thanks again for such a detail explanation, it helps a lot. thanks

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by