merging elements into a single cell array

7 views (last 30 days)
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 Comments
Satarupa Khamaru
Satarupa Khamaru on 6 Nov 2017
Hi James,thanks a lot for your quick assistance. Yes, all rows have exactly three elements.
Image Analyst
Image Analyst on 6 Nov 2017
Can you save B to a .mat file and upload it so we can try to work with it?

Sign in to comment.

Answers (1)

James Tursa
James Tursa on 6 Nov 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 Comments
James Tursa
James Tursa on 7 Nov 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 on 7 Nov 2017
Thanks again for such a detail explanation, it helps a lot. thanks

Sign in to comment.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!