merging elements into a single cell array

조회 수: 6 (최근 30일)
Satarupa Khamaru
Satarupa Khamaru 2017년 11월 6일
댓글: Satarupa Khamaru 2017년 11월 7일
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
Satarupa Khamaru
Satarupa Khamaru 2017년 11월 6일
Hi James,thanks a lot for your quick assistance. Yes, all rows have exactly three elements.
Image Analyst
Image Analyst 2017년 11월 6일
Can you save B to a .mat file and upload it so we can try to work with it?

댓글을 달려면 로그인하십시오.

답변 (1개)

James Tursa
James Tursa 2017년 11월 6일
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
James Tursa
James Tursa 2017년 11월 7일
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 2017년 11월 7일
Thanks again for such a detail explanation, it helps a lot. thanks

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile 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