开发者

Getting an ArrayIndexOutOfBoundsException when working with markov chains

I have an array to store a set of coordinates for painting a piece of line. So here are some example coordinates

double[][] plotMatrix = {{10,20},{55,80},
                         {120,40},{225,30},
                         {327.5,100},
                         {427.5,30},
                         {529,60}};

The next step is to create a markov matrix which is two-dimensional.

Getting an ArrayIndexOutOfBoundsException when working with markov chains

First I count the times where a point from the left column is followed by a point in the top column. Since I want a line each point is followed by another single point. That means if we have {10,20} as input the propability of {55,80} being the next point is 100%.

I am not really sure about all this so please correct me!

So this is my matrix

double[][] markovMatrix = { {0.0,1.0,0.0,0.0,0.0,0.0,0.0},
                                    {0.0,0.0,1.0,0.0,0.0,0.0,0.0},
                                    {0.0,0.0,0.0,1.0,0.0,0.0,0.0},
                                    {0.0,0.0,0.0,0.0,1.0,0.0,0.0},
                                    {0.0,0.0,0.0,0.0,0.0,1.0,0.0},
                                    {0.0,0.0,0.0,0.0,0.0,0.0,1.0},
                                    {0.0,0.0,0.0,0.0,0.0,0.0,0.0}};

My algor开发者_如何学运维ithm:

    int seed = 0;
    int output = 0;

    for(int i = 0; i < 40;i++){
        double choice = r.nextDouble();

        double currentSum = 0.0;

        for(;output < markovMatrix.length;output++){

            currentSum += markovMatrix[seed][output];

            if(choice <= currentSum){
                break;
            }
        }

        System.out.println(output);
        polygon.lineTo(plotMatrix[output][0], plotMatrix[output][1]);

        seed = output;

        output = 0;
    }

My problem is that I get an ArrayOutOfBoundsException:7 when I try to access both plotMatrix and markovMatrix. However output is set to 0 at the end of each loop. Any ideas how to solve that problem?


I'm not quite sure if its the right answer,

but for(;output < markovMatrix.length;output++) will step from 0 to 7, while you only have 0 to 6 entries in markovMatrix.

Using for(;output < markovMatrix.length-1;output++) fixes the ArrayIndexOutOfBoundsException by stepping from 1 to 6.

However I suspect you really want to step from 0 to 6. And there lies your problem.


When are done looping with the inside loop output=7 which is the length of the array. You are supposed to skip that last iteration because your array indexes are from 0 to 6.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜