Creating a For loop for a Harmonic Series

22 vues (au cours des 30 derniers jours)
Leonardo Morales
Leonardo Morales le 8 Nov 2019
function x = HarmArray(last)
x=zeros(1,last);
for i=1:last
x(i)=1./last(i)
end
end
Keeps giving me this error:
''Index exceeds the number of array elements (1).''
Error in HarmArray (line 4)
x(i)=1/last(i)
  2 commentaires
Douglas Brunson
Douglas Brunson le 8 Nov 2019
I suspect that 'last' is an integer.
Douglas Brunson
Douglas Brunson le 8 Nov 2019
Hence, 'i' can only be one.

Connectez-vous pour commenter.

Réponses (1)

David Hill
David Hill le 8 Nov 2019
last is not an array; therefore last(i) does not work!
function x = HarmArray(last)
x=zeros(1,last);
for i=1:last
x(i)=1/i;%this should give you what you want
end
end
Alternatively, you would not need to use a loop.
x=ones(1,last)./(1:last);
h=cumsum(x);%provides harmonic series (1.0000 1.5000 1.8333 2.0833 2.2833 2.4500 ...)
  1 commentaire
Leonardo Morales
Leonardo Morales le 11 Nov 2019
Understood. Thank you both!

Connectez-vous pour commenter.

Catégories

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

Community Treasure Hunt

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

Start Hunting!

Translated by