Cell array with adjacents elements by a “from” vector and a “to” vector
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I have 2 vectors, A and B of equal dimension. Each value of A indicates the source element of the element given by its position. Each value of B indicates the target element of the element given by its position. Some values of A and B are NaN, but they have the same indices (they occupy the same positions in A and B). Some values of A and B may be repeated.
For example:
A=[NaN NaN NaN NaN NaN NaN 3 2 4 4 1 5 ... ];
B=[NaN NaN NaN NaN NaN NaN 1 6 2 8 9 1 ... ];
I would like to get a cell array, C, that is an adjacency list of these elements. That is, a cell array where each cell is a vector with the target elements, and its position is the source element. In this case it would be like this:
source () -> target (find())
3 -> 7 ()
2 -> 8 ()
4 -> 9 ()
4 -> 10 ()
1 -> 11 ()
5 -> 12 ()
On the other hand:
source (find()) -> target ()
7 () -> 1
8 () -> 6
9 () -> 2
10 () -> 8
11 () -> 9
12 () -> 1
Therefore:
C={[11], [8], [7], [9, 10], [12], [1], [6], [2], [8], [9], [1], ...};
I have managed to do it with “for”, but A and B are very large and it takes too long to calculate. Could it be done in batch?
Thanks in advance
0 Kommentare
Antworten (1)
Steven Lord
am 17 Mai 2024
What are you hoping to do with this list? Depending on the specific operations you're looking to perform you may want to create a graph or digraph from your list of sources and targets and then use the functions available for Graph and Network Algorithms to manipulate the graph or digraph.
5 Kommentare
Steven Lord
am 17 Mai 2024
A=[NaN NaN NaN NaN NaN NaN 3 2 4 4 1 5];
source = A(~isnan(A))
target = find(~isnan(A))
D = graph(source, target)
plot(D)
dist = distances(D, 4)
reachable = find(isfinite(dist))
So you can get from 4 to 4, 9, or 10.
allpaths(D, 4, 10)
In this simple case the list of all paths is short. Let's add a few more edges.
D = addedge(D, [4, 10], 8)
plot(D)
Now there are more ways to get from 4 to 10.
allpaths(D, 4, 10)
Siehe auch
Kategorien
Mehr zu Graph and Network Algorithms finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!