MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
Asked by Jung Hyun on 29 Dec 2012

I tried to solve this problem, but I could not implement.

Could you help me anything for this?

[Problem]

Mat1 ||| Mat2 ||| Mat3

1 2 ||| 1 3 ||| 2 6

1 3 ||| 2 6 ||| 2 5

2 4 ||| 3 1 ||| 3 1

3 1 ||| 3 5 ||| 5 2

4 5 |||

When there are 3 matrices(for example above), I want to get this result for the intersection rows in [column1 column2 matrixnumber] form.

The result for above example would be

1 3 1

1 3 2

2 6 2

2 6 3

3 1 1

3 1 2

3 1 3

It would be OK if the result is in the form [column1 column2 firstmatrix secondmatrix, ...]

1 3 1 2 2 6 2 3 3 1 1 2 3

For this problem, I want to use at most one for-loop.

Do you have any idea for this?

Thank you in advance.

*No products are associated with this question.*

Answer by Image Analyst on 29 Dec 2012

I have no idea what you want or how you got that output, but take a look at ismember(), and intersect() and similar functions.

Answer by Andrei Bobrov on 29 Dec 2012

Edited by Andrei Bobrov on 29 Dec 2012

M = {Mat1,Mat2,Mat3}; M1 = cat(1,M{:}); n = cellfun(@(x)size(x,1),M(:)); n1 = [0;cumsum(n)]; n2 = zeros(n1(end),1); n2(n1(1:end-1) + 1) = 1; n2 = cumsum(n2); [a,~,c] = unique(M1,'rows'); n3 = accumarray(c,n2,[],@(x){x}); t = cellfun(@numel,n3) > 1; out = [num2cell(a(t,:),2), n3(t)];

way with `intersect`

M = {Mat1,Mat2,Mat3}; n = nchoosek(1:numel(M),2); k = []; for j1 = 1:size(n,1) a = intersect(M{n(j1,:)}); k = [k; [a ones(size(a,1),1)*n(j1,:)]]; end [b,~,c] = unique(k(:,1:end-2),'rows'); k1 = accumarray(c,(1:numel(c))',[],@(x){x}); out = [num2cell(b,2), cellfun(@(x)unique(k(x,end-[1 0])),k1,'un',0)];

Image Analyst on 29 Dec 2012

I would have been nice if you'd included the code to generate Mat1, etc. so others could try it easily.

## 1 Comment

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/57588#comment_119625

Explain the first row. How is the intersection of 1 & 2 with 1 & 3 with 2 & 6 equal to 1 3 1??? The 1 intersects in Mat1 and Mat2 (because both Mat1 and Mat2 have a 1 in them), and the 2 intersects with Mat1 and Mat3, but there is no intersection of any number

with all threematrices (in that first row). In that first row, there is no number that is in all three matrices.And Mat1 has 5 rows while Mat2 and Mat3 have only 4 rows. How are you getting an output of 3 1 1 for the 5th row. And how are you generating a 6th and 7th row for your output when no matrix has that many rows?