Is there a way to vectorize the following loop in MATLAB?
for j = 1:length(cursor_bin)
cursor_bin(j) = mean(cursor(bin == j));
end
cursor_bin
, cursor
, and bin
are all vectors.
Vectorization is one of the core concepts of MATLAB. With one command it lets you process all elements of an array, avoiding loops and making your code more readable and efficient. For data stored in numerical arrays, most MATLAB functions are inherently vectorized.
Loop vectorization transforms procedural loops by assigning a processing unit to each pair of operands. Programs spend most of their time within such loops. Therefore, vectorization can significantly accelerate them, especially over large data sets.
Vectorization is the process of transforming a scalar operation acting on individual data elements (Single Instruction Single Data—SISD) to an operation where a single instruction operates concurrently on multiple data elements (SIMD).
accumarray
does just that:
cursor_bin = accumarray(bin(:), cursor(:), [], @mean);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With