フィルターのクリア

What is vectorization? Why use vectorization instead of loops?

51 ビュー (過去 30 日間)
Hans Scharler
Hans Scharler 2023 年 10 月 11 日
回答済み: Hans Scharler 2023 年 10 月 11 日
Over at Reddit, a user asked about vectorization vs. a loop. This is a fundemental concept in MATLAB. So, what is vectorization? Why use it instead of loops?

採用された回答

Hans Scharler
Hans Scharler 2023 年 10 月 11 日
Vectorization is about replacing explicit loops with matrix and vector operations. This can lead to more readable and efficient code. MATLAB is particularly well-suited for vectorized operations as it is designed to work with matrices and vectors natively.
Here's a normal loop approach to square each element in a vector.
n = 10;
vector = 1:n;
result = zeros(1, n);
% Use a loop to square each element of a vector
for i = 1:n
result(i) = vector(i)^2;
end
disp(result);
1 4 9 16 25 36 49 64 81 100
Here's how this looks with vectorization:
vector = 1:10;
% Square each element of a vector using vectorization
result = vector.^2;
disp(result);
1 4 9 16 25 36 49 64 81 100
The magic here is the ".^" which is an element-wise operation. You can also do this with ".*" and "./".

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangePrice and Analyze Financial Instruments についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by