How can I solve this problem using for loop?

1 次查看(过去 30 天)
for the given vector [2 2 5 8], without using sum() and diff() how can i perform 2*2 + 2*5 + 5*8 = 54. Using for loop. here the consicutive number are multiplied and then addition is performed.

回答(2 个)

Matt J
Matt J 2021-11-11
v=[2 2 5 8];
for i=1
result=v(1:end-1)*v(2:end).'
end
result = 54
  7 个评论
Matt J
Matt J 2021-11-11
编辑:Matt J 2021-11-11
I demonstrated to you in my original answer that it does give the summation. This is assuming the vector is a row vector, which it was in your original post.

请先登录,再进行评论。


Emmanuel
Emmanuel 2024-1-23
total = 0;
x = [2,2,5,8];
n = length(x);
for i =1:n-1
total = total + x(i)*x(i+1);
end
disp(total)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by