Creating a For loop for a Harmonic Series

20 views (last 30 days)
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)

Answers (1)

David Hill
David Hill on 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 ...)

Categories

Find more on Creating and Concatenating Matrices 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!