How to compute a vector using a for loop

6 ビュー (過去 30 日間)
Jared Gibson
Jared Gibson 2020 年 8 月 12 日
編集済み: Jared Gibson 2020 年 8 月 12 日
I'm having trouble trying to compute a third vector "c" using a for loop where cj = aj x bj.
There's two N-element vectors "a" and "b" defined as a= [1,1,1,1,.....1] and b = [2,2,2,2......2] where N = 1000000.
a = ones(1,N);
b = 2*ones(1,N);
In essence I'm trying to compare a for loop computation of c vs an element-wise multiplication of c, in terms of speed and efficiency

回答 (1 件)

Andreas Bernatzky
Andreas Bernatzky 2020 年 8 月 12 日
Hi Timothy,
I am not completely sure if I fully understand your question. Maybe you should post your post.
But what you want to do (as I understand):
c = [];
for(j=1:1:length(a))
c(j) = a(j) * b(j);
end
comparing speed and performance you could use the matlab profiler or just simply tic() toc() but I doubt that this is enough to really say something about performance. Maybe you should also search the web for some performance reviews for vector operations (maybe for other languages too).
  1 件のコメント
Jared Gibson
Jared Gibson 2020 年 8 月 12 日
編集済み: Jared Gibson 2020 年 8 月 12 日
Sorry if I wasn't a clear, but here's a better explanation for the question.
"Consider two N-element vectors ~a = [1, 1, · · · 1], ~b = [2, 2, · · · 2], which can be created with the Matlab commands a = ones(1,N); b = 2*ones(1,N); We will compute a third vector ~c, whose elements are given by cj = aj × bj . We want to compute ~c in two different ways: first, using a for loop, and second, using the elementwise operation .* . For both, we will use Matlab’s built-in “Run and Time” function (located in the ribbon next to Run) to see how long the code takes to run. In particular, test how long it takes for your computer to execute the code using these two different approaches for three different lengths of the vectors a and b: N = 1, 000, 000, N = 10, 000, 000, and N = 100, 000, 000."

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

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by