Pregunta

I have a set of Vectors Ai such that i = 1...N; where N can be really large andd vectors contains integers except 0. All vectors are in same length so that's good. I need a function of which the output is a cell array C (the data class is not necessarily cell btw) such that C indices are actually the vector elements and the cell contents are the i indices for A vectors that shares the content.

F : Ai --> C

Example:

A1 = [1 2 4], 
A2 = [3 4 5], 
A3 = [4 1 2]

the resulting C should be

C{1} = [1 3];
C{2} = [1 3];
C{3} = [2];
C{4} = [1 2 3];
C{5} = [2];

and of course I would like to avoid elementwise for loops.

¿Fue útil?

Solución

I misunderstood the first time, I believe this is correct now:

A = [1 2 4
     3 4 5
     4 1 2];


Av = num2cell(unique(A(:))', 1);
C = cellfun(@(x)(find(any((A == x)'))), Av, 'UniformOutput', false)

Results in

C{1} = [1 3];
C{2} = [1 3];
C{3} = [2];
C{4} = [1 2 3];
C{5} = [2];

Otros consejos

Not really sure whether I understand your goal correctly, but I think this will get you there most of the way:

Create all combinations with 1 element from the first vector, 1 from the second, and 1 from the third vector.

[X,Y,Z] = ndgrid([1 2 3 4 5], [3 4 5 6 7], [4 8 9 11 2])
[X(:) Y(:) Z(:)]

Knowing this it should not be too hard to figure out how to get all combinations between 2 vectors. and then adding all single elements should be trivial.

You may want to sort this to the second dimension and take all unique values.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top