Borrar filtros
Borrar filtros

How can I search or sort a cell array of vectors when the vectors have non-uniform length?

1 visualización (últimos 30 días)
Hello,
I've been trying to sort a 1xN cell array of vectors by the first element in the vector, where the vectors do not have the same length, without using a for loop. This problem can be reduced to being able to return the first element in the vector at each row of the cell array.
Specifically, I have an undirected graph where each each vector in a cell array has the node as the first element, and all of the nodes it is connected to in the elements after that.
Example: If Node 1 is connected to node 2 and 4, and Node 3 is connected to node 4, an unsorted cell array A representing this is: A = {[1,2,4];[3,4];[2,1];[4,1,3]}
I want to find some method of searching for the row of cell array A corresponding to node 2.
I've tried using the command sortrows([A{:}]), but having non-uniform vectors forces cell2mat to convert the cell array to a single row.
Also, I've tried A{:}(1) and A(1:4){1} to only return the first column in the cell array, but this causes a "Bad cell reference operation" error.
Would anyone happen to know of some easy way to do this without a for loop?
Thanks, Dennis
  2 comentarios
per isakson
per isakson el 8 de Mayo de 2015
Editada: per isakson el 8 de Mayo de 2015
"return the first element in the vector at each row of the cell array"
>> cellfun( @(vec) vec(1), A )
ans =
1
3
2
4

Iniciar sesión para comentar.

Respuesta aceptada

Dennis Yeh
Dennis Yeh el 9 de Mayo de 2015
Editada: Dennis Yeh el 9 de Mayo de 2015
From per isakson's response, answer became
function output = sortCell(input, col)
data = cellfun( @(vec) vec(col), input);
data = [data,(1:length(data))'];
data = sortrows(data)
output = input(data(:,2));
end

Más respuestas (0)

Categorías

Más información sobre Cell Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by