Reputation: 95
I would like to take all elements of a matrix to the power of a specific number. I have a matrix using the matrix extension set up like this:
let A matrix:make-constant 4 4 5
which gives a 4x4 matrix with values of 5 in there
Now I want to take all elements in the matrix to the same power, so say I want to take them to power 2, then I want to end up with a 4x4 matrix with numbers 25.
How can I do this?
Upvotes: 2
Views: 580
Reputation: 12580
You can do this a couple ways. The simplest is probably with matrix:times-element-wise
. Unfortunately, this will only work for integer powers greater than or equal to 1:
to-report matrix-power [ mat n ]
repeat n - 1 [
set mat matrix:times-element-wise mat mat
]
report mat
end
You can also convert the matrix to a list of lists, and then use map on that to raise each element to a power. This has the advantage of working with 0, fractional powers, and negative:
to-report matrix-power [ mat n ]
report matrix:from-row-list map [ map [ ? ^ n ] ? ] matrix:to-row-list mat
end
map [ ? ^ n ] some-list
raises each element of a list to the power of n
. matrix:to-row-list
converts the matrix to a list of lists. So, we apply map [ ? ^ n ]
each list in the result of matrix:to-row-list
. Then, we convert the result back into a matrix with matrix:from-row-list
.
You can generalize this to do any element-wise operation:
to-report matrix-map [ function mat ]
report matrix:from-row-list map [ map function ? ] matrix:to-row-list mat
end
Then, we could define the power function as:
to-report matrix-power [ mat n ]
report matrix-map task [ ? ^ n ] mat
end
Upvotes: 1