Matrix-exponentiation operator: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: added syntax colouring, marked p2js compatible)
(→‎{{header|R}}: Syntax highlighting.)
Line 2,844: Line 2,844:
===Library function call===
===Library function call===
{{libheader|Biodem}}
{{libheader|Biodem}}
<lang R>library(Biodem)
<lang rsplus>library(Biodem)
m <- matrix(c(3,2,2,1), nrow=2)
m <- matrix(c(3,2,2,1), nrow=2)
mtx.exp(m, 0)
mtx.exp(m, 0)
Line 2,869: Line 2,869:
===Infix operator===
===Infix operator===
The task wants the implementation to be "as an operator". Given that R lets us define new infix operators, it seems fitting to show how to do this. Ideally, for a matrix a and int n, we'd want to be able to use a^n. R actually has this already, but it's not what the task wants:
The task wants the implementation to be "as an operator". Given that R lets us define new infix operators, it seems fitting to show how to do this. Ideally, for a matrix a and int n, we'd want to be able to use a^n. R actually has this already, but it's not what the task wants:
<lang r>a<-matrix(c(1,2,3,4),2,2)
<lang rsplus>a<-matrix(c(1,2,3,4),2,2)
a^1
a^1
a^2</lang>
a^2</lang>
Line 2,882: Line 2,882:
[2,] 4 16</pre>
[2,] 4 16</pre>
As we can see, it instead returns the given matrix with its elements raised to the nth power. Overwriting the ^ operator would be dangerous and rude. However, R's base library suggests an alternative. %*% is already defined as matrix multiplication, so why not use %^% for exponentiation?
As we can see, it instead returns the given matrix with its elements raised to the nth power. Overwriting the ^ operator would be dangerous and rude. However, R's base library suggests an alternative. %*% is already defined as matrix multiplication, so why not use %^% for exponentiation?
<lang r>`%^%`<-function(mat,n)
<lang rsplus>`%^%`<-function(mat,n)
{
{
is.wholenumber<-function(x,tol=.Machine$double.eps^0.5){abs(x - round(x))<tol}#See the docs for is.integer
is.wholenumber<-function(x,tol=.Machine$double.eps^0.5){abs(x - round(x))<tol}#See the docs for is.integer