Search code examples
matlabintersection

Intersection with N matrices in MATLAB


I have a matrix IntialMat, and I have a structure with N other matrices. I want to have the indices of the matrices that intersect with a least one element of the matrix IntialMat. How can I do that in MATLAB?

For example InitialMat=[2, 5, 88; 55 63 4] And structure MatriciesStor have N matrices :

Mat1=[1, 55,12; 45 78]
Mat2=[12, 14; 42,165]
Mat3=[2,18,11; 13,80; 10, 99]
.
.
.
.
.
.
MatN=[4, 77;63,20]

The result that I want is the value of the intersection and the name of the matrice or its index: the value 2 with Mat3 (index 3) The value 4 with MatN (index N)


Solution

  • You can loop over the matrices like this:

    IntialMat = randi(100, 3);
    for i = 1:10
        MatriciesStor{i} = randi(100, 3);
    end
    
    % Now compare all Mats against IntialMat
    for i = 1:10
        inter = intersect(MatriciesStor{i},IntialMat);
        if ~isempty(inter)
            fprintf("\nMatrix %d has intersections: %d", i, inter);
        end
    end
    fprintf("\n");
    

    which gives something like:

    Matrix 1 has intersections: 18 
    Matrix 2 has intersections: 46 
    Matrix 3 has intersections: 18 38 
    Matrix 7 has intersections: 79 
    Matrix 8 has intersections: 51 
    Matrix 9 has intersections: 75