필터 지우기
필터 지우기

Invalid Index in position 2

조회 수: 2 (최근 30일)
kevin cecere palazzo
kevin cecere palazzo 2019년 10월 4일
답변: Daniel M 2019년 10월 4일
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

답변 (2개)

Walter Roberson
Walter Roberson 2019년 10월 4일
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)

Daniel M
Daniel M 2019년 10월 4일
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

카테고리

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