How to determine frequency of a specific matrix row in MATLAB?
8 views (last 30 days)
Show older comments
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 Comments
Rik
on 6 Oct 2023
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]?
Answers (2)
Rik
on 6 Oct 2023
Edited: Rik
on 6 Oct 2023
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 Comments
William Rose
on 6 Oct 2023
Moved: Rik
on 6 Oct 2023
[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 Comments
See Also
Categories
Find more on Get Started with MATLAB in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!