sparse matrix operations to gain efficiency

6 views (last 30 days)
I've never really used sparse matrices before but I was wondering if it would be useful in my case to imporve efficiency. My code is as follows
kf=rand(1,reac); kb=rand(1,reac);
for i=1:reac
a=randi([1 3],1,5);b=randi([1 spec],1,5);
c=randi([1 3],1,5);d=randi([1 spec],1,5);
I've used an example of reac=25 and spec=20 but in reality I could have reac up to 1500 and spec up to 500. I use the values of rate in differential equations which I solve using ode15s. This is the part of my code that takes the longest, where fwd and bcwd are sparse matrices. Would truning them into sparse matrices using sparse help me? if so, how can I rewrite my code?
An help is appreciated,
Thank you!
Cedric Wannaz
Cedric Wannaz on 16 Jul 2019
Edited: Cedric Wannaz on 16 Jul 2019
It is likely more complex than this.
The gain in performance obtained from using sparse matrices generally involves building vectors I, J, and V of row and column indices and values of non-zero elements, and building a sparse matrix in one shot with a call like
S = sparse( I, J, V, nRows, nCols ) ;
You can easily build I using REPELEM and V using RANDI. But building J is not direct and you must enforce unique values (per row) otherwise the accumlating behavior of SPARSE will produce a side effect that you may not want.
To illustrate this behavior, look at the following:
>> S = sparse( [1 2 1], [1 2 1], [10 20 30], 2, 2 )
S =
(1,1) 40
(2,2) 20
Here you can see that as there were two elements (10 and 30) with same indices (1,1), the values were accumulated (summed) and S(1,1)=10+30=40.
PS: if you wanted to enforce uniqueness, you could use RANDPERM, but it won't allow you to generate J in one shot as far as I can tell.

Sign in to comment.

Accepted Answer

John D'Errico
John D'Errico on 16 Jul 2019
Are those matrices mostly zero? No. It looks like they are 50% zeros. Sparse will not gain anything, because thre is also overhead in working with computations on sparse matrices.
Next, sparse matrices gain when you are doing matrix multiplications, and solving linear systems of eequations, but mainly only then if they are really sparse. 50% zeros does not cut it.
AM on 16 Jul 2019
I realize now there is no difficulty in using sparse matrices here, I will test out my code and see which way is more efficient, thank you for your time!
(I had tried to use sparse matrices but had made a mistake in my code so I thought they were handled differently, sorry)

Sign in to comment.

More Answers (0)


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!