How to multiply two matrices using a list of lists in Io language?

196 Views Asked by At

I am learning the Io language and would like to know how to multiple matrices together using lists of lists.

Here is my code so far:

mA := List clone
mA := list(list(1, 2, 3), list(4, 5, 6), list(7, 8, 9))
mB := List clone
mB := list(list(1, 2, 3), list(4, 5, 6), list(7, 8, 9))
mC := List clone
mC := list(list(0, 0, 0), list(0, 0, 0), list(0, 0, 0))

i := 0
j := 0
k := 0

for(i, 0, mA size,
    for(j, 0, mB size (at(0)),
        for(k, 0, mB size,
            mC atPut(mC at(i) at(j), mC at(i) at(j) + mA at(i) at(k) * mB at(k) at(j))
        )
    )
)

When I run this code through it says there is an error saying "nil does not respond to '*'". So where I am actually multiplying inside the nested for loops, it's going into the list out of bounds. At least that is what I think it is doing, therefore the error. I'm not really sure what else to change the for loops to. I've even changed them to 2 and 3 since that's the size of the matrix lists I am trying to test, but got the same error.

1

There are 1 best solutions below

0
On BEST ANSWER

For starters, this error occurs when the index is trying to look for a position that is not in the array.

Set it to size-1 so you don't receive a 'nil' value

The other problem is that the output ends up looking like this:

list(81, 55, list(0, 0, 0))

How I fixed it was by using a temporary list, a temporary sum value, and the append method:

            for(i, 0, mA size-1,
              tempList := List clone
              for(j, 0, mB size (at(0))-1,
                sum := 0
                for(k, 0, mB size-1,
                  sum = sum + mA at(i) at(k) * mB at(k) at(j)
                   )
                   tempList append(sum)
                 )
                 mC atPut(i,tempList)
               )

With this, you should end up with this as your matrix:

list(list(30, 36, 42), list(66, 81, 96), list(102, 126, 150))