views:

709

answers:

6

This is what i have so far but I do not think it is right.

for (int i = 0 ; i < 5; i++)
{
    for (int j = 0;  j < 5; j++)
    {
        matrix[i][j] += matrix[i][j] * matrix[i][j];
    }
}
+9  A: 

Suggestion: if it's not a homework (if it is, please tag it correctly) don't write your own linear algebra routines, use any of the many peer reviewed libraries that are out there.

Now, about your code, if you want to do a term by term product, then you're doing it wrong, what you're doing is assigning to each value it's square plus the original value (n*n+n or (1+n)*n, whatever you like best)

But if you want to do an authentic matrix multiplication in the algebraic sense, remember that you had to do the scalar product of the first matrix rows by the second matrix columns (or the other way, I'm not very sure now)... something like:

for i in rows:
    for j in cols:
        result(i,j)=m(i,:)·m(:,j)

and the scalar product "·"

v·w = sum(v(i)*w(i)) for all i in the range of the indices.

Of course, with this method you cannot do the product in place, because you'll need the values that you're overwriting in the next steps.

Also, explaining a little bit further Tyler McHenry's comment, as a consecuence of having to multiply rows by columns, the "inner dimensions" (I'm not sure if that's the correct terminology) of the matrices must match (if A is m x n, B is n x o and A*C is m x o), so in your case, a matrix can be squared only if it's square (he he he).

And if you just want to play a little bit with matrices, then you can try Octave, for example; squaring a matrix is as easy as M*M or M**2.

fortran
A: 

It's been too long since I've done matrix math (and I only did a little bit of it, on top), but the += operator takes the value of matrix[i][j] and adds to it the value of matrix[i][j] * matrix[i][j], which I don't think is what you want to do.

Thomas Owens
A: 

Well it looks like what it's doing is squaring the row/column, then adding it to the row/column. Is that what you want it to do? If not, then change it.

+4  A: 
ephemient
A: 

First you need to know how matrix multiplication works.

Interactive guide here.

Milan
+5  A: 

That's not any matrix multiplication definition I've ever seen. The standard definition is

for (i = 1 to m)
   for (j = 1 to n)
      result(i, j) = 0
      for (k = 1 to s)
         result(i, j) += a(i, k) * b(k, j)

to give the algorithm in a sort of pseudocode. In this case, a is a m x s matrix and b is an s x n, the result is a m x n, and subscripts begin with 1..

Note that multiplying a matrix in place is going to get the wrong answer, since you're going to be overwriting values before using them.

David Thornley