How can I solve this problem using for loop?
显示 更早的评论
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 个)
v=[2 2 5 8];
for i=1
result=v(1:end-1)*v(2:end).'
end
7 个评论
DGM
2021-11-11
Oof. I missed the requirement to have a superfluous loop. I guess I flunked that test.
Manav Divekar
2021-11-11
DGM
2021-11-11
You'll have to describe how it's not working for you.
Manav Divekar
2021-11-11
That's not what I proposed. I had
b = m(1:end-1)*m(2:end).';
Manav Divekar
2021-11-11
Emmanuel
2024-1-23
0 个投票
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)
类别
在 帮助中心 和 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!