Creating a For loop for a Harmonic Series
22 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
Réponses (1)
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 ...)
Voir également
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!