How to fix this error: Attempted to access x(84); index out of bounds because numel(x)=83.

1 view (last 30 days)
I've been trying to write some code that mimics a Markov Model.
Code:
for i = 2:steps
if ((x(i-1) == 15) || (x(i-1) == -15))
if (x(i-1) == 15)
if (randsign(px) == 1)
x(i) = 15;
elseif (randsign(px) == -1)
x(i) = 14;
end
end
if (x(i-1) == -15)
%randsign(px);
if (randsign(px) == 1)
x(i) = -14;
elseif (randsign(px) == -1)
x(i) = -15;
end
end
else
x(i) = x(i-1) + randsign(px);
end
end
The "randsign" function randomly spits out either -1 or 1 and the boundaries lie between -15 and 15. Once the matrix hits 15 or -15 the code states that the next matrix value should either stay at 15 or -15, respectively, or move. I've tried initializing the matrix with zeros first (x=zeros(1,steps)), but I would observe something odd such that when the matrix value eventually gets to 15 or -15, the following index is skipped...
This is also shown here (after creating a matrix of zeros):
Columns 307 through 324
13 14 15 *15 0* -1 0 -1 0 1 0 1 0 -1 0 -1 -2 -3
I would really appreciate the help if you could give me some advice on how to solve this issue... Thanks!

Accepted Answer

Roger Stafford
Roger Stafford on 26 Apr 2014
I think your trouble is with the way you call on what you call 'randsign'. You state that "The 'randsign' function randomly spits out either -1 or 1", and you write:
if (randsign(px) == 1)
x(i) = 15;
elseif (randsign(px) == -1)
x(i) = 14;
end
Unfortunately, if the first 'randsign' were to yield -1 and second one a +1, and if you haven't previous assigned zeros to x(i), then x(i) will remain unassigned. Consequently on the next trip through the for-loop when you try to access x(i-1), matlab will complain that x doesn't have that many elements. This 'randsign' behavior also accounts for the sudden jump to zero you obtained when x was initially set to zeros. That particular value of x was skipped for the above reason.
To avoid this, simply change the above code to:
if (randsign(px) == 1)
x(i) = 15;
else
x(i) = 14;
end
and similarly with the other section of code using 'randsign'. Then you are guaranteed that x(i) will have an assigned value.
In any case you should always initially allocate the desired size for x before beginning the for-loop.

More Answers (0)

Categories

Find more on Performance and Memory 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!