How to determine frequency of a specific matrix row in MATLAB?
6 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Rik
il 6 Ott 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]?
Risposte (2)
Rik
il 6 Ott 2023
Modificato: Rik
il 6 Ott 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 Commenti
William Rose
il 6 Ott 2023
Spostato: Rik
il 6 Ott 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 Commenti
Vedere anche
Categorie
Scopri di più su Get Started with MATLAB in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!