Outer products are faster with b*b' in matlab?
Show older comments
I have a column vector with about 6800 elements, many of which are 0. How can I quickly calculate the multiplication of the column vector and its transpose?
a = rand(77,1);
b = [a; zeros(6800,1)]
tic
v = b*b';
% 0.053078s
toc
tic
v = bsxfun(@times, b, b.');
%0.066428s
toc
5 Comments
Bruno Luong
on 23 Sep 2024
Edited: Bruno Luong
on 23 Sep 2024
How so you intend to use v later? The best way would be do not compute v explicitly (1 rank matrix) but store it as simply as b. Then when you need to multiply v by an x a column vector, you will do
a = b'*x; % a is a scalar
vx = b * a;
You could store b as sparse matrix as suggested by @Sandeep Mishra
If the 0s is always at the same place why bother to multiply them in to loop
A = rand(77,100);
tic
n1 = 0;
for i = 1:100
a = A(:,i);
b = [a; zeros(6800,1)];
n1 = n1 + b*b';
end
toc
tic
n3 = 0;
for i = 1:100
a = A(:,i);
n3 = n3 + a*a';
end
n3(end+6800,end+6800) = 0;
toc
norm(n1-n3,'fro') % Check is they are equal
Bruno Luong
on 23 Sep 2024
If you know A befre hand yes. You never state that in your question.
Accepted Answer
More Answers (0)
Categories
Find more on Startup and Shutdown 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!