generate a digraph using a cell array and an array
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I'm trying to generate a digraph that shows the mapping between the array [1:10] to this cell array:
1×10 cell array
Columns 1 through 6
{[1 5 7]} {[2 3 4 5 7]} {[1 2 3 5 6 7 8]} {[2 4 5 7 9]} {[1 3 6 7 9]} {[2 4 6 8 9 10]}
Columns 7 through 10
{[1 7 9 10]} {[1 3 4 5 6 9 10]} {[1 3 4 5 8 10]} {[5 9 10]}
So 1 maps to 1, 5 and 7; 2 maps to 2, 3, 4, 5, and 7 and so on. Is there a way to do that?
Thank you.
0 commentaires
Réponse acceptée
Cris LaPierre
le 29 Nov 2023
I think you want to use this syntas: G = digraph(s,t)
This example is helpful: https://www.mathworks.com/help/matlab/ref/digraph.html#mw_26035adf-ff90-4a33-a8f8-42048d7e39a6
You need an element for each edge in s and t. You can achieve that with a little creativity
e = [{[1 5 7]} {[2 3 4 5 7]} {[1 2 3 5 6 7 8]} {[2 4 5 7 9]} {[1 3 6 7 9]} {[2 4 6 8 9 10]} ...
{[1 7 9 10]} {[1 3 4 5 6 9 10]} {[1 3 4 5 8 10]} {[5 9 10]}]
% Determine how many elements are in each cell
n = cellfun(@numel,e)
% Extract all values from the cell array to a target vector, t
t = [e{:}]
% use cumsum to find indices of first value from each cell
idx = cumsum([1,n(1:end-1)])
% Create s as a source vector of zeros the same size as t
s=zeros(size(t))
% Set index corresponding to fist cell value to 1
s(idx) = 1
% Use cumsum to create a vector of sources that aligns with t
s = cumsum(s)
% Create digraph
G = digraph(s,t);
plot(G,'Layout','force')
3 commentaires
Steven Lord
le 29 Nov 2023
Another solution uses repelem:
e = [{[1 5 7]} {[2 3 4 5 7]} {[1 2 3 5 6 7 8]} {[2 4 5 7 9]} {[1 3 6 7 9]} {[2 4 6 8 9 10]} ...
{[1 7 9 10]} {[1 3 4 5 6 9 10]} {[1 3 4 5 8 10]} {[5 9 10]}];
% Determine how many elements are in each cell
n = cellfun(@numel,e);
% Extract all values from the cell array to a target vector, t
t = [e{:}];
% The new part
s = repelem(1:numel(e), n)
G = digraph(s,t);
plot(G,'Layout','force')
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Graph and Network Algorithms dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!