How to find the number of occurrences of each pair in a matrix?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Md Shahidullah Kawsar
am 30 Okt. 2018
Beantwortet: Bruno Luong
am 31 Okt. 2018
Suppose my
A = [1 2 3;
2 3 1;
2 1 3]
% where any digit won't repeat in the same row.
% I need to find out the number of occurrences of each pair.
Expected output:
Pair(1,2) = 1 occurence;
Pair(2,1) = 1;
Pair(2,3) = 2;
Pair(3,2) = 0;
Pair(3,1) = 1;
Pair(1,3) = 1;
I was trying this code
for n = 2:3
[j,i]=ind2sub(fliplr(size(A)), strfind(reshape(A.',1,[]),[1 n]).');
C = [i,j];
d = numel(C(j));
T9 = table(1, n, d)
end
error occurs when the second row ends with 1 and the third row begins with 2.
0 Kommentare
Akzeptierte Antwort
Bruno Luong
am 31 Okt. 2018
A = [1 2 3;
2 3 1;
2 1 3];
u = unique(A);
P = nchoosek(u,2);
P = [P;fliplr(P)];
[~,J] = ismember([A(:,1:2); A(:,2:3)],P,'rows');
n = accumarray(J(:),1,[size(P,1) 1]);
%
for k=1:size(P,1)
fprintf('Pair %s, %d time\n',mat2str(P(k,:)),n(k));
end
Output
Pair [1 2], 1 time
Pair [1 3], 1 time
Pair [2 3], 2 time
Pair [2 1], 1 time
Pair [3 1], 1 time
Pair [3 2], 0 time
0 Kommentare
Weitere Antworten (1)
David Goodmanson
am 31 Okt. 2018
Bearbeitet: David Goodmanson
am 31 Okt. 2018
Hi MSK,
nrow = size(A,1);
B = A(:);
s1 = full(sparse(B(1:end-nrow),B(nrow+1:end),1))
puts instances if i,j into entry i,j. This should work with any number n of columns, assuming numbers 1 through n are used in each row.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Waveform Generation finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!