論理行列において、T​rueの個数を各列ご​とで数えたい

14 vues (au cours des 30 derniers jours)
miya
miya le 7 Nov 2022
Commenté : miya le 7 Nov 2022
■やりたいこと
論理行列で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
Parent-1
└─ child-1 └─ child-2 └─ child-3
Parent-2
└─ child-1 └─ child-2
Parent-3
└─ child-1
Parent-4
└─ child-1 └─ child-2 └─ child-3

Réponse acceptée

Atsushi Ueno
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
Parent-1
└─ child-1 └─ child-2 └─ child-3
Parent-2
└─ child-1 └─ child-2
Parent-3
└─ child-1
Parent-4
└─ child-1 └─ child-2 └─ child-3
  1 commentaire
miya
miya le 7 Nov 2022
早速の回答ありがとうございます。
sum関数でできますね…。言われてみればそうでした…。
解決したので、クローズします。

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!