Summation and for looping in matlab

284 Views Asked by At

I have a basic code that I'm struggling to make it work on matlab. Any help would be appreciated.

M = [1 2 3 4 5];

for t=1:5;

if t<2;

    fx=10*exp(-0.1)

else 

    fx=sum(5.*exp(-0.1*(t)))+10*exp(-0.1*M(t))

    end 

end

so I am essentially trying to find the present value of the discounted cash flows at different years. I get an output however I realised that from the 3rd year, matlab does not discount the cashflows from year 1 up to year 3 but rather finds the value at year 3 only. i.e.

$$5\exp(-0.1)+5\exp(-0.2)+5\exp(-0.3)+10\exp(-0.3)$$ is what I actually want but what matlab outputs is

$$5\exp(-0.3)+10\exp(-0.3)$$

and so forth for the other years.

How do I fix this such that I can get the correct present values?

1

There are 1 best solutions below

0
On

Within the loop t is an indexing variable, that means it has a scalar value. Replace your line

fx=sum(5.exp(-0.1(t)))+10*exp(-0.1*M(t))

with

fx=sum(5.exp(-0.1(1:t)))+10*exp(-0.1*M(t))

and it should work. (I created a new vector 1:t instead of your scalar t)