I have some problems with the efficiency of my code. Basically my code works like this:
a = zeros(1,50000);
for n = 1:50000
a(n) = 10.*n - 5;
end
sum(a);
What is the fastest way to solve the sum of all the elements of this matrix?
I have some problems with the efficiency of my code. Basically my code works like this:
a = zeros(1,50000);
for n = 1:50000
a(n) = 10.*n - 5;
end
sum(a);
What is the fastest way to solve the sum of all the elements of this matrix?
Copyright © 2021 Jogjafile Inc.
first you want to remove your for loop by making it a vector multiplication:
An alternative way is to simplify your operation, you are multiplying 1 to 50000 by 10 and subtracting 5 then taking the sum (which is a single number), which is equivalent to:
or if you are really into Math (this is a pure mathematical expression approach) :
and as you can see, a little math can do greater good than pure efficient programming, and actually, loop is not always slow, in your case, the loop is actually faster than the vectorized method:
Timing
Let's do some timing and see the results. The function to run it yourself is provided at the bottom. The approximate execution time
execTimeis in seconds and the percentage of improvementimpPercentagein %.Results
R2016a on OSX 10.11.4
Code
The following function can be used to generate the output. Note that it requires minimum R2013b to be able to use the built-in
timeit-function andtable.