help counting number of times a value occurs across matrix
55 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I have an 19x100 matrix, dp, that can have a variety of values in it
111, 112, 121, 122, 211, 212, 221, 222, 311, 312, 321, 322, 411, 412, 421, 422
I want to count the number of times each value occurs in the matrix, thus, the number for each count should never be more than 100 and the sum of all the counts across each row should be 100
I've tried using the sum function but that doesn't seem to be working with the way I have it set up
count_111 = sum(dp == 111,2);
I thought this would sum up the number of times 111 occurs across each row but it's summing 111 with all the 111
Which function should I use to just count the number of times each value occurs?
4 Kommentare
Antworten (2)
Matt J
am 4 Nov. 2024 um 22:34
values = [111, 112, 121, 122, 211, 212, 221, 222, 311, 312, 321, 322, 411, 412, 421, 422];
edges=[values,inf];
dp = [111 112 121 111 211; 111 111 321 411 111]
for i=1:height(dp)
counts(i,:)=histcounts(dp(i,:),edges);
end
counts
0 Kommentare
Bruno Luong
am 5 Nov. 2024 um 8:06
Bearbeitet: Bruno Luong
am 5 Nov. 2024 um 9:30
Alternative way of counting
% Random test array
A = round(10 + 2 * randn(3,10))
% Count #repetitions by row
[value,~,J] = unique(A);
[m,n] = size(A);
I = repmat(1:m,1,n);
C = accumarray([I(:),J],1);
% Make nice output
Counts = num2cell(C.',1);
Varnames = sprintfc('CountRow%d', 1:m);
CountTable = table(value, Counts{:}, VariableNames = ['Value', Varnames])
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!