topaz has asked for the wisdom of the Perl Monks concerning the following question:

Hi I have a list of $a $b values which can go from (-180 --- 180)

For example: 100 2 -2 44 150 9 26 -4 150 9 0 -1

I want to create a 2 dimensional array 361x361 and set it to zero then start recording the count of combination $a $b the combination of 150 and 9 appeared twice on the list so the count will be 2 can I do something like this ?

my @a = ((0) x 361); my @b = ((0) x 361); my @matrix = (@a,@b) while ($line = <IN>) { @record = split(/\s+/, $line); $a = $record[0]; $b = $record[1]; @matrix [$a+180][$b+180] ++; }

Replies are listed 'Best First'.
Re: 2 D array
by ikegami (Patriarch) on Jul 28, 2011 at 22:05 UTC

    The following creates 361 + 361 cells, not 361 x 361:

    my @a = ((0) x 361); my @b = ((0) x 361);

    For* each of the 361 rows, you need to create 361 cells.

    * — Hint!

      @row = ((0) x 361); @column = ((0) x 361); my @Matrix = ( @row, @column); ?

        You didn't change anything but the names of the variables?!? That's still the same as

        my @Matrix = (0) x (361*2);

        You want to end up with something equivalent to

        my @Matrix = ( [ (0) x 361 ], [ (0) x 361 ], [ (0) x 361 ], ... 355 more ... [ (0) x 361 ], [ (0) x 361 ], [ (0) x 361 ], );

        Unless you want 361 identical lines, you'll want some kind of loop...

        (I'm treating this as homework. Whether it's personal or assigned doesn't matter to me.)

        Keep in mind that an array is a list of scalar "things".

        Luckily, since array references are scalar "things", your primary array can be made to hold 361 scalar references, each of which is referencing a unique 361-element array.

        For those "secondary" arrays, your job is to somehow create 361 lists (arrays) and still be able to access them as scalar references. But hey, you can get one of those with [(0) x 361]

        You only need to push 360 more onto the primary list where you stored that first one. :-)

        Note: thanks to ikegami for pointing out the mistake with my previous statement that:

        @row = ((0) x 361); is creating a one-element list whose element is a scalar string of 361 zeros.('0000000000000000 ... 00000')

Re: 2 D array
by BrowserUk (Patriarch) on Jul 29, 2011 at 04:36 UTC

    Just a thought, but if these dimensions are rotations in degrees, then -180 and +180 are the same place, so you would only need 360 not 361 elements in your array(s).


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.