How to SUM certain values of vector without using any loop?

I have a vector : y[n] , containing n values.I want to do this sum:
111.png
I can do it with a loop like this:
for k = 2:(m+1)
p=p+y((2*k)-1);
end
Is there way to do this sum without a for/while loop cycle?
Thank you.

 Accepted Answer

p = sum(y(2*(2:m+1) - 1));
You seem to be uncomfortable with the expression 2:m+1. Note that + has a higher precedence in the order of operations than colon, so m+1 is done first, THEN the colon operator runs. Personally, I agree it a good habit to use parens when there is any doubt.
So nothing will stop you from writing:
p = sum(y(2*(2:(m+1)) - 1));
Or, if you want to make it somewhat more readable, you can expand it as:
k = 2:m+1;
p = sum(y(2*k - 1));

More Answers (1)

Thank you very much:) very helpful, that expanded form is nice trick

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!