0

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
2
  • sum is also the name of an internal function of MATLAB. Try to avoid such variable names, as in your example you couldn't use the sum function after running this code (until clearing the sum variable) Commented Sep 30, 2015 at 5:49
  • @hbaderts thanks for suggestion. i will avoid it. Commented Sep 30, 2015 at 7:22

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use sum native function:

total = sum(1:50);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.