フィルターのクリア

matrix multiplication without declaring the destination matrix first

1 回表示 (過去 30 日間)
Elinor Ginzburg
Elinor Ginzburg 2019 年 10 月 29 日
コメント済み: Elinor Ginzburg 2019 年 10 月 30 日
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 件のコメント
dpb
dpb 2019 年 10 月 29 日
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
Elinor Ginzburg 2019 年 10 月 30 日
thank you very much! the problem was that without the ';' matlab printed the matrix, and it took some time.

サインインしてコメントする。

回答 (1 件)

Matt J
Matt J 2019 年 10 月 29 日
編集済み: Matt J 2019 年 10 月 29 日
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 件のコメント
Elinor Ginzburg
Elinor Ginzburg 2019 年 10 月 30 日
thank you, I've found the problem - missins ';' after the zeros command. it took some time to print the matrix...

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by