How to efficiently sum values in matrix using indices from a logical statement of a different matrix
조회 수: 4 (최근 30일)
이전 댓글 표시
I have two 2D matrices, A and B which are of the same size. The values of A are my output values, and the values of B are the probabilities of each value in A. So, prob(A(i,j)) = B(i,j). I expect there to be many repetitions in A (not each output is unique) so I want to find two vectors, one which tells me the unique values of A and the other which tells me the probability of each of those unique values.
I know I can use the unique() function to find the unique values of A. But currently, my approach to finding the probability of each unique value (looping and summing - see example below) is by far the slowest part of my code. Is there a faster way to do this?
%Set up matrix of values
A = [0 1 2 3;
1 2 3 4;
2 3 4 5];
%Set up matrix of probabilities
B = [0.05 0.02 0.03 0.10;
0.10 0.30 0.10 0.05;
0.10 0.05 0.05 0.05];
%Find vector of unique values of A
uniA = unique(A);
%Find probabilities of each value of A (This is what I want to make more
%efficient)
prob_uniA = zeros(size(uniA));
for i = 1:length(uniA)
prob_uniA(i) = sum(B(A == uniA(i)));
end
Notes: In reality, my A and B matrices are approximately 1000x1000. I am looking to improve the speed because this process is implemented within a for loop with ~15 iterations (and will be applied to 200 different datasets in the future, so small gains in size here make a big difference in overall time). I am running a 2020 Mac Mini with M1 chip, 16GB memory.
Thanks!
댓글 수: 0
채택된 답변
the cyclist
2023년 3월 28일
편집: the cyclist
2023년 3월 28일
%Set up matrix of values
A = [0 1 2 3;
1 2 3 4;
2 3 4 5];
%Set up matrix of probabilities
B = [0.05 0.02 0.03 0.10;
0.10 0.30 0.10 0.05;
0.10 0.05 0.05 0.05];
% Find the unique values of A, and the indices that map each original value
% to the unique ones
[uniA,~,k] = unique(A);
% Sum the probabilities via the mapping created
prob_uniA = accumarray(k,B(:))
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!