create a new variable that is the product of lag value of another variable and its own lag value

my two input variables are age and mortality,
I want to create another variable "survival = 1" for first value of "age" like here first value of age = 65, but it can be any age
then for following ages 66, 67, 68 onwards, it should take the value from previous survival value at age 65 and mutliply with corresponding (1-mortality).
for example, my two input variables are age and mortality,
age mortality
65 0.0347029096019856
66 0.0382583912888586
67 0.0421156045159524
68 0.0463212051920102
69 0.0509158865323249
70 0.0559879627737633
my output variable is survival
age mortality survival
65 0.0347 1
66 0.0382 1*(1- 0.0347) = 0.9653
67 0.0421 0.9653 *(1-0.0382) = 0.9284
68 0.0463 0.9284*(1-0.0421) = 0.8898
.
.
.
.
This is the code which I had written but it is giving wrong values. I do not know whether I should for-loop or is there an easy way out.
survival = ones(size(age))
for i = 2 : length(???)
survival = survival(i-1,:).*(1-mortality(1:end-1,:))
end
I would appreciate your help!

 Réponse acceptée

survival=cumprod(1-mortality);

3 commentaires

Thank you for your hep. It works,
but I also need to have "1" as the first value of "survival"
and for the rest,
survival = cumprod(1-mortality) is completely fine.
%you can do it the long way round:
survival=cat(1+(size(mortality,1)<size(mortality,2)),1,cumprod(1-mortality(1:(end-1))));
%or pick the correct one from these:
survival=[1;cumprod(1-mortality(1:(end-1))))];
survival=[1,cumprod(1-mortality(1:(end-1))))];
I figured that out, it should be,
survival = ones(size(age))
survival(2:end,:) = cumprod(1-mortality(1:end-1,:))

Connectez-vous pour commenter.

Plus de réponses (0)

Question posée :

le 18 Août 2020

Commenté :

le 18 Août 2020

Community Treasure Hunt

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

Start Hunting!

Translated by