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.

Antworten (2)

Matt J
Matt J am 11 Nov. 2021
v=[2 2 5 8];
for i=1
result=v(1:end-1)*v(2:end).'
end
result = 54

7 Kommentare

DGM
DGM am 11 Nov. 2021
Oof. I missed the requirement to have a superfluous loop. I guess I flunked that test.
Manav Divekar
Manav Divekar am 11 Nov. 2021
Sorry this is not working
DGM
DGM am 11 Nov. 2021
You'll have to describe how it's not working for you.
function [out] = pairprodsum (m)
s = 0
for i = 1
b = m(1:end-1).*m(2:end);
s = s + b;
end
out = s;
If i use it in this i am just able to get the multiplied array, i am trying to get the sum also
Matt J
Matt J am 11 Nov. 2021
Bearbeitet: Matt J am 11 Nov. 2021
That's not what I proposed. I had
b = m(1:end-1)*m(2:end).';
Manav Divekar
Manav Divekar am 11 Nov. 2021
this is giving a matrix, not the summation.
Matt J
Matt J am 11 Nov. 2021
Bearbeitet: Matt J am 11 Nov. 2021
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.

Melden Sie sich an, um zu kommentieren.

Emmanuel
Emmanuel am 23 Jan. 2024

0 Stimmen

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)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2021a

Tags

Gefragt:

am 10 Nov. 2021

Beantwortet:

am 23 Jan. 2024

Community Treasure Hunt

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

Start Hunting!

Translated by