Problem
In MATLAB I have 2 1-D array of the same size with integer values. Considering that the values at a same index are a pair, I want to count how many pairs of each I have and store that in a matrix to later print it a a heatmap.
Here is a small example of what I want to archive:
v1 = [1, 0, 1, 0, 1];
v2 = [1, 1, 0, 1, 1];
% Magic happens here
heatMatrix = [0, 2;
1, 2];
The result is as follow because we have:
- 0 time the pair v1=0, v2=0 (heatMatrix[1, 1])
- 2 times the pair v1=0, v2=1 (indices 2 and 4, heatMatrix[1, 2])
- 1 time the pair v1=1, v2=0 (index 3, heatMatrix[2, 1])
- 2 time the pair v1=1, v2=1 (indices 1 and 5, heatMatrix[2, 2])
My code
I have done that using MATLAB loops which is slower than reasonable especially for long vectors:
% Alocating random vectors
rng(0);
maxVal = 255;
nbElem = 1e6;
v1 = randi(nbElem, 1);
v2 = randi(nbElem, 1);
heatMatrix = zeros(maxVal, maxVal);
% Creating heat matrix
tic();
for ii = 1:maxVal
for jj = 1:maxVal
heatMatrix(ii, jj) = sum((v1 == i) & (v2 == j));
end
end
toc();
Performance issues
I have to deal with long vectors, in the realm of 1e7 elements. I am working with an Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz and have 7.5 GB of RAM. And my performances are as follow:
Question
I am looking for a way to speed up the execution of this task. I'm mostly looking for a way to vector or perform the task in a smarter way (maybe there is a MATLAB function I'm not aware of).
