Fastest method of modifying elements of a matrix based on multiple indexes
2 views (last 30 days)
Show older comments
I am trying to arrive at the fastest method of modifying the elements of a matrix based on more than 1 index for the elements in that matrix to be modified. So I have set up a simple problem and tested 4 different methods as follows:
ynum = 100;
xnum = 100;
P = int8(randi(2,ynum,xnum)-1);
C = rand(ynum,xnum);
mu = zeros(ynum,xnum); % preallocate
% indexes
idx0 = (P==0);
idx1 = (P==1);
% sparse indexes
idx0_sp = sparse(idx0);
idx1_sp = sparse(idx1);
%%TESTS
% method 1
tic
for k=1:10000
mu(idx0)=2.2.*C(idx0)-0.65;
mu(idx1)=2.2.*C(idx1)-1.55;
end
toc
% method 2
tic
for k=1:10000
mu=2.2*C-0.65;
mu(idx1)=2.2*C(idx1)-1.55;
end
toc
% method 3
tic
for k=1:10000
mu(idx0_sp)=2.2.*C(idx0_sp)-0.65;
mu(idx1_sp)=2.2.*C(idx1_sp)-1.55;
end
toc
% method 4
tic
for k=1:10000
mu=2.2*C-0.65;
mu(idx1_sp)=2.2*C(idx1_sp)-1.55;
end
toc
from which I get
Elapsed time is 2.870694 seconds.
Elapsed time is 1.459029 seconds.
Elapsed time is 0.701292 seconds.
Elapsed time is 0.446436 seconds.
So I find:
1. As modifying all elements of a matrix is much faster than modifying an index of elements within that matrix, I get a significant speedup by completely ignoring one index (idx0), and instead modifying all elements of the matrix, then modifying the elements of the second index (idx1). Unfortunately, this means that modifying a matrix with a logical index is quite slow. Speed will increase as the number of logical true elements decreases, but the operation remains generally slow. This is too bad because this method cannot work if idx0=1-idx1. Can this be sped up by implementing a MEX function for this basic operation, or anything else, at all? Or is the slowdown inherent to the operation?
2. I recently discovered that converting a logical index to a sparse logical index is very helpful, as is clear from my experiments.
Can anything else be done to improve speed?
0 Comments
Answers (0)
See Also
Categories
Find more on Sparse Matrices 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!