# Vectorize product cell vectors

5 views (last 30 days)
Alvaro Borras on 6 Nov 2021
Answered: Srivardhan Gadila on 17 Nov 2021
I need to efficiently compute the quantity where and , , are vectors and are sparse matrices.
If the matrices were not sparse, then I could use a 3D array and probably vectorize some of the operations.
Right now, I am using a cell structure to store the matrices and I store the vectors in matrices.
Here's the relevant part of the code that I am using:
res = 1;
for k = 1:N
res = res * (u(:, k).' * A{k} * v(:, k));
end
For reference, in my case and 0, and the loop takes about 2 seconds. In my code, this loop is called several times, so it would make a great impact to reduce its runtime.
How can I improve the performance of the loop? Can it be vectorized? Should I be computing it in another way?
Thank you.

Srivardhan Gadila on 17 Nov 2021
I think that, you are already representing the matrices of the cell array A in the sparse form and in that case you are already having the best performance. You can refer to the documentation page of Sparse Matrices and the following MATLAB Answer: Is there a faster way to multiply a sparse and full matrix than standard multiplication in Matlab? for any additional information.
Although, I have tried experimenting the code by making use of gpuArray, and it seems that for m = 100,000 and n = 100 it was consuming less time of all, on my machine. At the same time for lower values of m it is slower. Once try executing the below code:
clc; clear all
%%
m = 100000; N = 100;
u = randn(m,N); v = randn(m,N);
ug = gpuArray(u); vg= gpuArray(v);
A = {}; As = {}; Asg = {};
for i = 1:N
As{i} = sprand(m,m,1/m);
A{i} = full(As{i});
Asg{i} = gpuArray(As{i});
end
%% Not using sparse representation
tic
res = 1;
for k = 1:N
res = res * (u(:, k).' * A{k} * v(:, k));
end
toc
%% Using sparse representation
tic
res = 1;
for k = 1:N
res = res * (u(:, k).' * As{k} * v(:, k));
end
toc
%% Using arrayfun
tic
res = arrayfun(@(k)fun(As,u,v,k),1:N);
res = prod(res);
toc
%% Using gpuArray
tic
res = 1;
for k = 1:N
res = res * (ug(:, k).' * Asg{k} * vg(:, k));
end
toc
function out = fun(A,u,v,k)
out = (u(:, k).' * A{k} * v(:, k));
end

### Categories

Find more on Loops and Conditional Statements 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!

Translated by