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.

 采纳的回答

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));

更多回答(1 个)

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

类别

在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by