Jump to content

Matrix-exponentiation operator: Difference between revisions

→‎{{header|R}}: Syntax highlighting.
m (→‎{{header|Phix}}: added syntax colouring, marked p2js compatible)
(→‎{{header|R}}: Syntax highlighting.)
Line 2,844:
===Library function call===
{{libheader|Biodem}}
<lang Rrsplus>library(Biodem)
m <- matrix(c(3,2,2,1), nrow=2)
mtx.exp(m, 0)
Line 2,869:
===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:
<lang rrsplus>a<-matrix(c(1,2,3,4),2,2)
a^1
a^2</lang>
Line 2,882:
[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?
<lang rrsplus>`%^%`<-function(mat,n)
{
is.wholenumber<-function(x,tol=.Machine$double.eps^0.5){abs(x - round(x))<tol}#See the docs for is.integer
331

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.