Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Summation and for looping in matlab

Writer Olivia Zamora
$\begingroup$

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?

$\endgroup$ 2

1 Answer

$\begingroup$

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)

$\endgroup$

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy