필터 지우기
필터 지우기

intersect between the second column of cell array A (for all rows) and the first column of cell array B (for all rows)

조회 수: 4 (최근 30일)
I want to intersect between the second column of cell array A (for all rows) and the first column of cell array B (for all rows).
I tried
[H,ih,ik]=intersect(A{:,2},B{:,1});
but an error is resulting:
Error using intersect
Too many input arguments.
What I am doing wrong?
Thank you.

채택된 답변

Steven Lord
Steven Lord 2021년 11월 8일
Let's make some sample cell arrays with animal names. [I'm assuming your cell arrays contain text data.]
animals = {'dog','cat','fish','horse'};
rng default
A = animals(randi(numel(animals), 5, 2))
A = 5×2 cell array
{'horse'} {'dog' } {'horse'} {'cat' } {'dog' } {'fish' } {'horse'} {'horse'} {'fish' } {'horse'}
B = animals(randi(numel(animals), 5, 2))
B = 5×2 cell array
{'dog' } {'dog' } {'horse'} {'cat' } {'horse'} {'horse'} {'cat' } {'horse'} {'horse'} {'horse'}
Instead of using {} to extract the elements of the second column of A and the first column of B (which would result in a comma-separated list), use () to extract the columns themselves (which results in smaller cell arrays.)
[C, IA, IB] = intersect(A(:, 2), B(:, 1)) % Use () to extract a sub-cell array
C = 3×1 cell array
{'cat' } {'dog' } {'horse'}
IA = 3×1
2 1 4
IB = 3×1
4 1 2

추가 답변 (2개)

Jon
Jon 2021년 11월 8일
편집: Jon 2021년 11월 8일
The problem is that A{:,2} and B{:,1} are not returning arrays but instead multiple answers. So somthing like this:
>> A = {1,2,3;4,5,6}
A =
2×3 cell array
{[1]} {[2]} {[3]}
{[4]} {[5]} {[6]}
>> A{:,2}
ans =
2
ans =
5
you could try
[H,ih,ik]=intersect([A{:,2}],[B{:,1}]);
That is surround the results by square brackets to consolidate them into arrays. If this doesn't help then please copy an example piece of code that shows the problem, and in particular defines your A and B cell arrays, and I can try to help you further
  댓글 수: 2
Jon
Jon 2021년 11월 8일
Here's a little snippet from the MATLAB documentation
Concatenation
Putting a comma-separated list inside square brackets extracts the specified elements from the list and concatenates them:
A = [C{:,5:6}]
A =
34 36 38 40 42 44 46 48

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


dpb
dpb 2021년 11월 8일
This may or may not be possible with simple syntax depending upon the content of the cell arrays...if it can work,
[H,ih,ik]=intersect([A{:,2}],[B{:,1})];
The curlies {} return a comm-separated list; the [] will gather that into a vector if the cell content is not nested.
The simpler solution in that instance would be to use cell2mat() on A and B first and get rid of the cell arrays; there wouldn't be any need to keep pure numeric data as a cell array to begin with.
If it is nested, then you'll have to dereference the underlying content appropriately.

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by