If statement not replacing matrix elements correctly

4 次查看(过去 30 天)
Hello I have created a nested if loop inside a for loop which tries to iterate on a matrix produced previously from another for loop.
The if statement should basically go through each element in said matrix, if the result is less than zero then equate it to zero, otherwise leave the element as it is.
I have pasted my script below and I am referring specifically to the nested if statement inside the forloop in the end of my script.
%Parameter declaration for coding:
dr = 0.02;
vol = 0.3;
S = 160;
r = 0.04;
T = 3;
simnum = 3 %no of simulations
%Computation of ALL iteration constants
%Step1: Compute K
K = 1.1 * (S-(dr*S)*exp(-r));
%Step2: Compute Dividend Value
dv = dr * S;
%Step3: Compute adjusted S
sadj = S - dv*exp(-r*T);
%Step 4 Computed Discount rate
disc = exp(-r*T);
%Step 5 Computation of Deterministic part
fx = sadj*exp(r-0.5*(vol^2))*T+vol*sqrt(T)
%Simulation for Stochastic part
tic
sim = 1:1:simnum;
a = 1:1:simnum;
Scomp = 1:1:simnum;
%C = 1:1:simnum
cpo = disc*Scomp - K
for i = 1:simnum
a(i) = normrnd(0,1);
Scomp(i) = fx * a(i)
end
toc
% Payoff matrix creation
cpoff = disc*Scomp - K
%cpoffcorr = zeros(1,simnum)
for i = 1:simnum
if cpoff > 0
cpoffcorr(i) = cpoff
else
cpoffcorr(i) == 0
end
end
% Average and Variance Computation
%CBAR = cpoffcorr/simnum
%CVAR = var(CBAR)

采纳的回答

Voss
Voss 2022-5-25
编辑:Voss 2022-5-25
I think you mean:
cpoffcorr = zeros(1,simnum); % yes, pre-allocate
for i = 1:simnum
if cpoff(i) > 0 % check the ith element
cpoffcorr(i) = cpoff(i) % assign using the ith element
else
cpoffcorr(i) = 0 % use assignment (=) not comparison (==)
end
end
However, you can do it without a loop at all:
cpoffcorr = max(0,cpoff)
  2 个评论
Mahmoud Galal
Mahmoud Galal 2022-5-25
that was very straightforward, thank you very much, the cpoffcorr = max(0,cpoff) did the trick, it did not work for me earlier since I was trying to for loop it.
Need to learn to think that things are simpler than they are.
Thanks again!!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by