Effacer les filtres
Effacer les filtres

How can I solve this problem using for loop?

2 vues (au cours des 30 derniers jours)
Manav Divekar
Manav Divekar le 10 Nov 2021
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.

Réponses (2)

Matt J
Matt J le 11 Nov 2021
v=[2 2 5 8];
for i=1
result=v(1:end-1)*v(2:end).'
end
result = 54
  7 commentaires
Manav Divekar
Manav Divekar le 11 Nov 2021
this is giving a matrix, not the summation.
Matt J
Matt J le 11 Nov 2021
Modifié(e) : Matt J le 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.

Connectez-vous pour commenter.


Emmanuel
Emmanuel le 23 Jan 2024
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)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Tags

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by