Løsningsforslag - oppgaver i Avsnitt 1.6.7


Oppgave 1

  public Matrise(int m, int n, int verdi)
  {
    if (m < 0) throw new
      IndexOutOfBoundsException("m(" + m + ") er negativ!");

    if (n < 0) throw new
      IndexOutOfBoundsException("n(" + n + ") er negativ!");

    this.m = m;
    this.n = n;

    a = new int[m][n];

    for (int i = 0; i < m; i++)
    {
      for (int j = 0; j < n; j++)
      {
        a[i][j] = verdi;
      }
    }
  }

Oppgave 2

  public Matrise(Matrise A)
  {
    m = A.m;
    n = A.n;

    a = new int[m][n];

    for (int i = 0; i < m; i++)
    {
      for (int j = 0; j < n; j++)
      {
        a[i][j] = A.a[i][j];
      }
    }
  }

Oppgave 3

  public static Matrise enhet(int n)
  {
    if (n < 0) throw new
      IndexOutOfBoundsException("n(" + n + ") er negativ!");

    Matrise I = new Matrise(n,n);
    for (int i = 0; i < n; i++) I.a[i][i] = 1;
    return I;
  }

Oppgave 4

  public Matrise rad(int i)
  {
    if (i < 0 || i >= m) throw new
      IllegalArgumentException("Indeks i(" + i +") er utenfor matrisen!");

    Matrise A = new Matrise(1,n);

    for (int j = 0; j < n; j++)
      A.a[0][j] = a[i][j];

    return A;
  }

Oppgave 5

  public Matrise minus(Matrise B)
  {
    if (m != B.m || n != B.n)
      throw new IllegalArgumentException("B har feil dimensjon!");

    Matrise A = new Matrise(m,n);

    for (int i = 0; i < m; i++)
      for (int j = 0; j < n; j++)
        A.a[i][j] = a[i][j] - B.a[i][j];

    return A;
  }

Oppgave 6

  public Matrise ganger(int k)
  {
    Matrise A = new Matrise(m,n);

    for (int i = 0; i < m; i++)
    {
      for (int j = 0; j < n; j++)
      {
        A.a[i][j] = a[i][j]*k;
      }
    }
    return A;
  }

Oppgave 7

  public Matrise ganger(Matrise B)
  {
    if (n != B.m)
      throw new IllegalArgumentException("B har feil dimensjon!");

    Matrise Produkt = new Matrise(m,B.n);  // A*B

    for (int i = 0; i < m; i++)
    {
      for (int j = 0; j < B.n; j++)
      {
        int produktsum = 0;
        for (int k = 0; k < n; k++)
        {
          produktsum += a[i][k]*B.a[k][j];
        }
        Produkt.a[i][j] = produktsum;
      }
    }
    return Produkt;
  }

Oppgave 8

  public Matrise transponer()
  {
    Matrise A = new Matrise(n,m);

    for (int i = 0; i < m; i++)
      for (int j = 0; j < n; j++)
        A.a[j][i] = a[i][j];

    return A;
  }

Oppgave 9

  public String toString()
  {
    int maks = 0;

    for (int i = 0; i < m; i++)
    {
      for (int j = 0; j < n; j++)
      {
        int element = a[i][j];
        if (element < 0) element = -element;
        if (element > maks) maks = element;
      }
    }

    int bredde = Integer.toString(maks).length() + 2;

    Formatter f = new Formatter();

    for (int i = 0; i < m; i++)
    {
      for (int j = 0; j < n; j++)
      {
        f.format("%"+ bredde +"d",a[i][j]);
      }
      f.format("\n");
    }

    return f.toString();
  }