# Changing values in a matrix

I’ve got a 4 x 4 matrix (as a list of four lists) that is initially all zeros; i.e.
{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}} is viewed as:

``````       0  0  0  0
``````

M = 0 0 0 0
0 0 0 0
0 0 0 0 ,

and I want to populate it by changing some of the zeros to new numbers
to get something like this say (view it as a elements by row):

0 2 0 0
1 0 0 7
0 5 6 0
0 1 0 8 ,

But, set (item theColumn of (item theRow of M)) to NewNumber errors
because it won’t let me set zero to another number (obviously).
How do I replace the zero with my entry?

It should work provided neither theColumn nor theRow is greater than 4.

The problem turned out to be more subtle. For example, zeroing the matrix as follows:

``````
set aRow to {0, 0, 0, 0}
set mat to {aRow} & {aRow} & {aRow} & {aRow}
-- which results in a 4x4 of zeros
-- But then:
set item 2 of (item 3 of mat) to 3
mat
-- results in the second item of every row being set to
-- 3; each row reads {0, 3, 0, 0}

``````

I presume this is because AS has not allocated 16 positions for mat, but only
4. The only way to avoid this is to explicitly set all 16 elements of the 4x4.
In the code that started this thread I had done something similar.

Hi NovaScotian,

Your rows are sharing values. Instead, use copy:

set aRow to {0, 0, 0, 0}
set mat to {}
repeat 4 times
copy aRow to end of mat
end repeat
– which results in a 4x4 of zeros
– But then:
set item 3 of item 2 of mat to 5
mat

gl,