returning matices and pointers to them

Discussion in 'Mac Programming' started by Quboid, Sep 2, 2007.

  1. Quboid macrumors 6502

    Oct 16, 2006
    hey all,

    I am doing some homework here (for tomorrow) and the last few programs seem a bit tricky. I have the logic for the one i am doing now down already, however, it would require me returning a matrix from my function. I am not to keen on trying to return a matrix, instead i am looking at return a pointer to matrix created.

    how do i declare the function in this case?, and how do i declare the matrix in question?

    thanks a million
  2. zimv20 macrumors 601


    Jul 18, 2002
    simple. you can declare your matrix like this:
    type Matrix = array [ array [ real ] ]
    let's say you're performing an 8 neighbor relaxation. you can do something like this:
    function relax ( a : Matrix returns Matrix )
    for row in a at i cross elt in row at j
       avg := (elt   a[i, j-1]   a[i, j 1]  
               a[i 1, j-1]   a[i 1, j]   a[i 1, j 1]  
               a[i-1, j-1]   a[i-1, j]   a[i-1, j 1]) / 9.0
    returns array of avg
    end for
    end function
    so just specify your return type as Matrix, and return it when done.
  3. Quboid thread starter macrumors 6502

    Oct 16, 2006
    I'm sorry i forgot to specify that i am programming in c++.
  4. garethlewis2 macrumors 6502

    Dec 6, 2006
    Steps for you to do.

    Declare your function line the following.

    Mat3x3 blahFunction(something *) {
    // Mat3x3 can be a class, structure or for C a two-dim array
    if a class, use a new operator.
    if doing it like C, use malloc. and cast the malloced memory to the type

    // Do the operations on the matrix.

    // return the Mat3x3

    return mat3x3;

    At the top of your file, if a 3x3 array use the following.

    typedef double Mat3x3[3][3];

    And you can use it like the following

    Mat3x3 xyz, becomes a two dim array.

Share This Page