Mayur
Mayur

Reputation: 41

Vectorization MATLAB sum equation snippet

I am new to MATLAB, and would like to understand how we can vectorize below snippet, or how can i do it efficiently:

sum=0;
for i = 1:50
   sum=sum+i;
end

Upvotes: 0

Views: 41

Answers (2)

Evan Kravitz
Evan Kravitz

Reputation: 11

sum(1:50)

The above statement initializes a vector of length 50 starting from 1 to 50 (with increments of length 1), and then calls MATLAB's sum function on it, returning the sum of all elements in the vector.

Upvotes: 1

Prakash Bhagat
Prakash Bhagat

Reputation: 1446

You can use sum native function:

total = sum(1:50);

Upvotes: 0

Related Questions