dealing with negative indices error
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
please help, i keep getting this error: "Array indices must be positive integers or logical values."
Here is my code:
randn('state',100)
lambda = 2;
mu = 1;
Xnot = 1;
T = 1;
N = 2^8;
r = 0.5;
gamma = 0.5;
delta = 1-gamma;
dt = 1/N;
t = 0.5;
dW = sqrt(dt)*randn(1,N);
W = cumsum(dW);
R = 4;
Dt = R*dt;
L = N/R;
beta = 1.5;
eta = 2;
rho = 0.2;
v = r + (lambda-r)^2/2*delta*mu^2;
D = rho-(gamma*v);
G = delta*(1-exp((D/delta)*(t-T)));
H = (delta*eta)/beta
X_temp = Xnot;
for T = 1
t = -1:1
end
F = X_temp + (((delta*eta)/(beta*r))*(1-exp(r(t-T))));
C = ((D*F)/G)-H;
M = (lambda-r)/(delta*mu^2)
J = (eta*(lambda-r))/(beta*r*mu^2)*X_temp;
pi = M+J
X_EM = zeros(1,L);
for j = 1:L
Winc = sum(dW(R*(j-1)+1:R*j));
X_temp = X_temp + Dt*((pi*(lambda-r)+r)-C) + (mu*pi)*Winc;
X_EM(j) = X_temp;
end
plot([0:Dt:T],[Xnot,X_EM],'g-', 'LineWidth', 2)
1 Commento
Rik
il 16 Lug 2019
Have you tried using breakpoints to find out where your code deviates from what you expect?
Risposte (2)
Star Strider
il 16 Lug 2019
There turned out to be three problelms with your code that I corrected here.
The original one was due to your forgetting an operator, that I assume should be a multiplication:
F = X_temp + (((delta*eta)/(beta*r))*(1-exp(r*(t-T))));
↑
The second is that ‘X_EM’ was not preallocated correctly, and not addressed correctly, since each ‘X_temp’ is a (1x3) vector:
X_EM = zeros(L,3);
for j = 1:L
Winc = sum(dW(R*(j-1)+1:R*j));
X_temp = X_temp + Dt*((pi*(lambda-r)+r)-C) + (mu*pi)*Winc;
X_EM(j,:) = X_temp;
end
The third was that the dependent variable in the plot call was not concatenated correctly, now that ‘X_EM’ is a matrix:
plot([0:Dt:T],[Xnot*ones(1,3);X_EM],'g-', 'LineWidth', 2)
With these changes, your code works.
2 Commenti
Walter Roberson
il 16 Lug 2019
for T = 1
t = -1:1
end
After that T is the scalar 1 and t is -1 0 1
F = X_temp + (((delta*eta)/(beta*r))*(1-exp(r(t-T))));
t-T is -1 0 1 minus 1, so -2 -1 0.
r is a scalar so r(t-T) is a request to index r at -2 -1 0
0 Commenti
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!