How to determine frequency of a specific matrix row in MATLAB?
조회 수: 11 (최근 30일)
이전 댓글 표시
In MATLAB I want to calculate the frequency that a row with specific column values occurs in a matrix, e.g. how frequent is the row [7 2 4]. How can I do this?
I have three columns A, B and C.
I must determine how frequently C=4 when it is the case that A=7 and B=2? Can I do this in a loop for all possible combinations of A and B when C=4?
댓글 수: 2
Rik
2023년 10월 6일
This is not too hard to do with logical vectors. What have you tried so far?
And do you want the frequency of C=4 given that A=7 and B=2, or do you want the overall frequency of [7 2 4]?
답변 (2개)
Rik
2023년 10월 6일
편집: Rik
2023년 10월 6일
Let's first create the same variables William created:
N=10000;
A=randi(9,N,1); B=randi(9,N,1); C=randi(9,N,1);
X=[A,B,C];
W=[7,2,4];
Since the goal is to find the frequency of rows with full matches provided the first two already match, we will need some extra steps. If not, ismember would do the trick.
% This only works if W is a row vector, so you could use this:
% W = reshape(W,1,[]);
FirstAllMatch = all( X(:,1:(end-1)) == W(1:(end-1)) ,2);
LastMatch = X(:,end) == W(end);
MatchFrequency = mean(FirstAllMatch & LastMatch);
disp(MatchFrequency)
ConditionalMatchFrequency = sum(FirstAllMatch & LastMatch)/sum(FirstAllMatch);
disp(ConditionalMatchFrequency)
If you want to do some analysis to find all the places where the third element is equal to some value, you can simply use X(:,3)==SomeInteger and calculate what you need from the resulting logical vector.
댓글 수: 0
William Rose
2023년 10월 6일
이동: Rik
2023년 10월 6일
[edit: change [7,4,2] to [7,2,4] to agree with the original question]
Suppose A, B, C are vectors of length N, and each contains the integers 1 to 9 at random:
N=10000;
A=randi(9,N,1); B=randi(9,N,1); C=randi(9,N,1);
Combine the vectors to make a 3-column matrix
X=[A,B,C];
Find the occurrences of rows with [7,2,4]:
W=[7,2,4];
numWinX=0;
for i=1:N
if X(i,:)==W
numWinX=numWinX+1;
end
end
fprintf('Number of Ws in array X=%d.\n',numWinX)
That is a way to do it.
Others will probably be able to provide a more elegant solution, i.e. a solution that does not use a for loop.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!