matrix multiplication without declaring the destination matrix first
Show older comments
hey,
I'm trying to multiply two matrices (I don't want to use any shortcuts, I want to do the multiplication by defention). can I do it without declaring first on the matrix?
what I wrote is:
C2 = zeros(N)
for i = 1:N
for j = 1:N
for k = 1:N
C2(i,j) = C2(i,j) + A(i,k)*B(k,j);
end
end
end
but the action of C2 = zeroes(N) is time consuming since N=1000 in this case. anyway to skip this declaration?
Thank you!
3 Comments
It will be even more time consuming if you skip it. The time is spent allocating memory, which is done once here. It will be done multiple times if you remove it. You will also get an M-Lint warning basically telling you this if you get rid of it.
You should terminate it with a ; though. It takes fractions of a seconod on my machine with the ; on the end.
dpb
on 29 Oct 2019
C2(N,N)=0;
may be even a tiny fraction faster...whatever it takes, it's a nit in comparison to not preallocting for larger arrays.
Elinor Ginzburg
on 30 Oct 2019
Answers (1)
You can loop backwards. Then the pre-allocation will be done silently.
clear C2
for i = N:-1:1
for j = N:-1:1
for k = 1:N
C2(i,j) = C2(i,j) + A(i,k)*B(k,j);
end
end
end
However, I don't know why you think the zeros command is the slow part of the code. I also don't know why you care about speed. The only reason it would make sense to do this is as a homework exercise, in which case speed should not be the issue.
1 Comment
Elinor Ginzburg
on 30 Oct 2019
Categories
Find more on Matrix Indexing 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!