Help with matrices.

Discussion in 'Mac Programming' started by theAdolescent, Feb 17, 2009.

  1. macrumors newbie

    Feb 1, 2009
    When you are adding two matrices together, you add similar elements together and place them in a new matrix. Because of this, you need to have matrices with identical sizes. Create a Matrix class, with methods such as add(Matrix a), subtract(Matrix a) and multiplyScalar(double n).

    I'm wondering right now how to assign my matrix to a class.
    Could anyone help?
    This is what I've got.

    import java.util.Scanner;
    public class tenpointtwo {
        public static void main(String[] args) {
            String input;
            Scanner in = new Scanner(;
            final int ROWS = 3;
            final int COLUMNS = 3;
            String[][] myMatx = new String[ROWS][COLUMNS];
            for (int r = 0; r < ROWS; r++)
                for (int c = 0; c < COLUMNS; c++) {
                    input =;
                   myMatx[r][c] = input;
  2. macrumors 68040


    Jan 10, 2005
    Dallas, TX
    Some general tips:
    Matrices are normally mathematical constructs, and their elements are some sort of numbers. You are using strings for storage. I would change this to int if your matrices are going to only contain whole numbers, or double if floating point numbers.

    I would not hardcode dimensions in your matrix class. that is really limiting the utility of the class. You should have member variables that contain the dimensions, and have a constructor that accepts the dimensions desired. When the constructor is called, it can initialize your actual backing store of a two dimensional int/double array to the sizes passed in. You wouldn't HAVE to have member variables, you could "ask" the array for its dimensions each time you need to check them, but it seems like members would be "cleaner".

    As an extension of the above point, when your addMatrix method is called, you can verify that the dimensions match before continuing with the operation. if they do not you can throw an InvalidArgument exception, or your own custom exception, or handle the error in some other way.

    Also, a lot of advice was given in this previous thread:

    You may want to re-read that before proceeding.


Share This Page