論理行列において、Trueの個数を各列ごとで数えたい
조회 수: 5 (최근 30일)
이전 댓글 표시
■やりたいこと
論理行列で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
채택된 답변
Atsushi Ueno
2022년 11월 7일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!