How can I solve this problem using for loop?
Show older comments
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.
Answers (2)
v=[2 2 5 8];
for i=1
result=v(1:end-1)*v(2:end).'
end
7 Comments
DGM
on 11 Nov 2021
Oof. I missed the requirement to have a superfluous loop. I guess I flunked that test.
Manav Divekar
on 11 Nov 2021
DGM
on 11 Nov 2021
You'll have to describe how it's not working for you.
Manav Divekar
on 11 Nov 2021
That's not what I proposed. I had
b = m(1:end-1)*m(2:end).';
Manav Divekar
on 11 Nov 2021
Emmanuel
on 23 Jan 2024
0 votes
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)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!