plctwincatcodesysstiec61131-3

How to assign an initialized array to an array of arrays in TwinCAT


I'm trying to assign two initialized arrays evenNumbers and oddNumbers to an array of arrays integers:

PROGRAM ArrayInit
VAR
    evenNumbers : ARRAY[1..3] OF INT := [2, 4, 6];
    oddNumbers: ARRAY[1..3] OF INT := [1, 3, 5];
    
    integers : ARRAY[1..2] OF ARRAY[1..3] OF INT := [evenNumbers, oddNumbers];
END_VAR

This code gives me a compiler error

Array initialisation expected

Of course I can directly initialize integers with the numbers that I want like so:

PROGRAM ArrayInit
VAR
    integers: ARRAY[1..2] OF ARRAY[1..3] OF INT := [
        [2, 4, 6], [1, 3, 5]
    ];
END_VAR

or like Sergey mentioned

PROGRAM ArrayInit
VAR
    integers: ARRAY[1..2, 1..3] OF INT := [
        2, 4, 6, 1, 3, 5
    ];
END_VAR

However, if the original arrays are very big and/or I want to document what these different arrays are, a descriptive name would be nice. I.e. integers : ARRAY[1..2] OF ARRAY[1..3] OF INT := [evenNumbers, oddNumbers]; nicely shows that the integers has two lists, one with even and one with odd numbers.

I've also tried to initialize integers as integers: ARRAY[1..2] OF ARRAY[1..3] OF INT := [[evenNumbers], [oddNumbers]];, but this gives me the compiler error:

Cannot convert type 'ARRAY [1..3] OF INT' to type 'INT'

Now I wonder if it even possible? If so, does anyone know how I can do it?


Solution

  • To assign multiple level array you do it in one line.

    combinedSet : ARRAY[1..2, 1..2] OF INT := [1,2,3,4];
    

    will result in array

    [
      1 => [
         1 => 1, 
         2 => 2
      ],
      2 => [
         1 => 2, 
         2 => 4
      ]
    ]
    

    SO first it assign all element of first element [1, 1], [1, 2], [1, 3] ... and then nest one [2, 1], [2, 2], [2, 3] ...

    Additional information

    Most simple way to merge 2 arrays into one multi dimensional is:

    PROGRAM PLC_PRG
        VAR
            arr1 : ARRAY[1..3] OF INT := [1,3,5];
            arr2 : ARRAY[1..3] OF INT := [2,4,6];
            combinedSet : ARRAY[1..2] OF ARRAY[1..3] OF INT;
        END_VAR
        
        combinedSet[1] := arr1;
        combinedSet[2] := arr2;
    END_PROGRAM
    

    The reason this does not work

    integers : ARRAY[1..2] OF ARRAY[1..3] OF INT := [evenNumbers, oddNumbers];
    

    Because evenNumbers and oddNumbers are not initialized at the moment of use. If you would declare those in VAR CONSTANT it would probably work but then you would not be able to change content of those arrays in program.