# How to do a quick division between a column array and a matrix?

2 views (last 30 days)
Benson Gou on 28 Jan 2019
Commented: Benson Gou on 28 Jan 2019
Hello, All,
I want to divid a column array b (N x 1) by each column in a big sparse matrix A (N x M). My code is as follows:
dividCol = zeros(N,M);
for i = 1 : M
nonCol = find(abs(A(:,i))>0);
dividCol(nonCol,i) = b(nonCol)./A(nonCol,i);
end
But it is very slow. I do know if there exist a faster approach to write this code.
Benson

Omer Yasin Birey on 28 Jan 2019
Edited: Omer Yasin Birey on 28 Jan 2019
Hi Benson, try this
% b = randi(25,25,1);
% A = randi(25,25,5);
[row,col] = find(abs(A(:,:))>0);
dividCol = bsxfun(@rdivide,b(row,1),A(row,col));

Benson Gou on 28 Jan 2019
Hi, Omer,
Thanks for your help. I tested your code and found the following:
A is 7 x 14, b is 7 x 1. But I got dividCol is 61 x 61. The size of dividCol is not correct.
Thanks a lot again,
Benson
Omer Yasin Birey on 28 Jan 2019
Yes I checked the code and it does every operation twice. I had to use loop and updated the code. Try it instead.
% b = randi(25,7,1);
% A = randi(25,7,14);
for i = 1:M
nonCol = find(abs(A(:,i))>0);
dividCol = bsxfun(@rdivide,b(nonCol),A(nonCol,i));
end
Benson Gou on 28 Jan 2019
Omer,