論理行列において、Trueの個数を各列ごとで数えたい
14 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
■やりたいこと
論理行列でTrueの箇所を各列ごとにカウントしたい。
最終的には、列の数が親を表し、Trueの数が子を表すツリーを作成したい。
■やったこと & 質問
ひとまず、列ごとにTrueをカウントし、列の数を親、Trueの数を子とするツリーはできている。
しかし、For文が多くスマートさに欠けるので、もっと簡潔に書ける方法をご教授願いたい。
clc
A = [1 1 1 1; 1 1 0 1; 1 0 0 1]; % 入力
[row, col] = size(A); % 行、列 取得
cnt = zeros(1,col); % 列分 初期化
for c = 1:col % 1~最終列まで
for r = 1:row % 1~最終行まで
if A(r,c) == 1 % 1のとき
cnt(c) = cnt(c) + 1; % カウントアップ
end
end
end
for c = 1:col % 1~最終列まで
disp(append('Parent-',num2str(c))) % 親 表示
for r = 1:cnt(c) % 各列ごとにカウントした分まで
disp(append('└─ child-',num2str(r))) % 子 表示
end
end
0 commentaires
Réponse acceptée
Atsushi Ueno
le 7 Nov 2022
A = [1 1 1 1; 1 1 0 1; 1 0 0 1]; % 入力
cnt = sum(A,1); % Trueの箇所を各列ごとにカウント
for c = 1:size(A,2) % 1~最終列まで
disp(append('Parent-',num2str(c))) % 親 表示
for r = 1:cnt(c) % 各列ごとにカウントした分まで
disp(append('└─ child-',num2str(r))) % 子 表示
end
end
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Matrix Indexing 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!