필터 지우기
필터 지우기

generate a digraph using a cell array and an array

조회 수: 1 (최근 30일)
Keihan
Keihan 2023년 11월 28일
댓글: Cris LaPierre 2023년 11월 29일
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.

채택된 답변

Cris LaPierre
Cris LaPierre 2023년 11월 29일
I think you want to use this syntas: G = digraph(s,t)
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]}]
e = 1×10 cell array
{[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)
n = 1×10
3 5 7 5 5 6 4 7 6 3
% Extract all values from the cell array to a target vector, t
t = [e{:}]
t = 1×51
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
% use cumsum to find indices of first value from each cell
idx = cumsum([1,n(1:end-1)])
idx = 1×10
1 4 9 16 21 26 32 36 43 49
% Create s as a source vector of zeros the same size as t
s=zeros(size(t))
s = 1×51
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
% Set index corresponding to fist cell value to 1
s(idx) = 1
s = 1×51
1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0
% Use cumsum to create a vector of sources that aligns with t
s = cumsum(s)
s = 1×51
1 1 1 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 6 6 6 6 6
% Create digraph
G = digraph(s,t);
plot(G,'Layout','force')
  댓글 수: 3
Steven Lord
Steven Lord 2023년 11월 29일
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)
s = 1×51
1 1 1 2 2 2 2 2 3 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 6 6 6 6 6
G = digraph(s,t);
plot(G,'Layout','force')
Cris LaPierre
Cris LaPierre 2023년 11월 29일
+1 That's much cleaner.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Graph and Network Algorithms에 대해 자세히 알아보기

태그

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by