Invalid Index in position 2
2 views (last 30 days)
Show older comments
When I run, Matlab says "Index in position 2 is invalid. Array indices must be positive integers or logical values." I cannot find the error in the following code (ignore that plot function is missing in the end):
clc
clear all
N=50;
M=100;
B=11;
n=50;
s=zeros(N,M);
volat=ones(n,N);
s=zeros(N,M);
rng(11);
figure (1);
hold on
for k=1:N
eps=zeros(n,M);
eps(1,1)=volat(1,k)*randn(1,1);
auxmtx=zeros(M,B,2);
pstar=zeros(M,1);
for i=2:n
if eps(i-1,1)<0
volat(i,1)=0.01+0.89*volat(i-1,1)+0.2*(eps(i-1,1)^2);
else volat(i,j)=0.01+0.89*volat(i-1,1);
end
eps(i,1)=sqrt(volat(i,1))*randn(1,1);
end
s(k,1)=sum(eps(:,1))/sqrt(n);
for j=2:M
for l=1:n
if eps(l,1)>0
eps(l,j)=sqrt(volat(l,1))*abs(randn(1,1));
else
eps(l,j)=eps(l,1);
end
end
s(k,j)=sum(eps(:,j))/sqrt(n);
end
end
0 Comments
Answers (2)
Walter Roberson
on 4 Oct 2019
else volat(i,j)=0.01+0.89*volat(i-1,1);
At that point you have not assigned to j so it is the default sqrt(-1)
0 Comments
Daniel M
on 4 Oct 2019
First, rename the variable eps to something else, because you are overloading the built-in Matlab function eps() which is bad practice and could cause problems.
As a prime example of why you shouldn't use Matlab function names as variable names, your Invalid Index error is actually a result of doing this. In the first else statement, you haven't yet defined j, so it is resorting to its default complex value:
clear
j
ans =
0.0000 + 1.0000i
0 Comments
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!