Element-wise operations: Difference between revisions
m
→{{header|Wren}}: Minor tidy
m (→{{header|Phix}}: added syntax colouring the hard way, phix/basics) |
m (→{{header|Wren}}: Minor tidy) |
||
(13 intermediate revisions by 10 users not shown) | |||
Line 25:
Using Generics, the task is quite trivial in Ada. Here is the main program:
<
procedure Scalar_Ops is
Line 55:
Ada.Text_IO.Put_Line(" M mod 2=" & Image(A mod 2));
Ada.Text_IO.Put_Line("(M*2) mod 3=" & Image((A*2) mod 3));
end Scalar_Ops;</
{{out}}
Line 70:
Our main program uses a generic package Matrix_Scalar. Here is the specification:
<
type Rows is (<>);
type Cols is (<>);
Line 85:
function Image(M: Matrix) return String;
end Matrix_Scalar;</
And here is the corresponding implementation. Note that the function Image (which we just use to output the results) takes much more lines than the function Func we need for actually solving the task:
<
function Func(Left: Matrix; Right: Num) return Matrix is
Line 133:
end Image;
end Matrix_Scalar;</
=={{header|ALGOL 68}}==
Line 140:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<
MODE SCALAR = REAL;
Line 193:
elementwise op(pow, matrix, matrix)
))
)</
{{out}}
<pre>
Line 227:
(2567686153161210000000000000000000000000000.00, 17069174130723200000000000000000000000000000000.00, 10555134955777600000000000000000000000000000000000000000000.00));
</pre>
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
main:
/* create an integer random array */
A=-1,{10}rand array(A), mulby(10), ceil, mov(A)
{","}tok sep
{"\ENF","ORIGINAL ARRAY :",A,"\OFF\n","="}reply(90),
println
{"Increment :\t"}, ++A,{A} println
{"Decrement :\t"}, --A,{A} println
{"post Increment: "}, A++, println
{*"\t",A} println
{"post Decrement: "}, A--, println
{*"\t",A} println
{"A + 5 :\t\t"}, {A} plus (5), println
{"5 + A :\t\t"}, {5} plus (A), println
{"A - 5 :\t\t"}, {A} minus (5), println
{"5 - A :\t\t"}, {5} minus (A), println
{"A * 5 :\t\t"}, {A} mul by (5), println
{"5 * A :\t\t"}, {5} mul by (A), println
{"A / 5 :\t\t"}, {A} div by (5), println
{"5 / A :\t\t"}, {5} div by (A), println
{"A \ 5 :\t\t"}, {A} idiv by (5), println
{"5 \ A :\t\t"}, {5} idiv by (A), println
{"A ^ 5 :\t\t"}, {A} pow by (5), println
{"5 ^ A :\t\t"}, {5} pow by (A), println
{"A % 5 :\t\t"}, {A} module (5), println
{"5 % A :\t\t"}, {5} module (A), println
{"SQRT(A) + 5:\t"}, {A} sqrt, plus(5),
tmp=0,cpy(tmp), println
{"--> CEIL :\t"} {tmp},ceil, println
{"--> FLOOR :\t"} {tmp},floor, println
{"A + A :\t\t"}, {A} plus (A), println
{"A - A :\t\t"}, {A} minus (A), println
{"A * A :\t\t"}, {A} mulby (A), println
{"A / A :\t\t"}, {A} div by (A), println
{"A \ A :\t\t"}, {A} idiv by (A), println
{"A ^ A :\t\t"}, {A} pow by (A), println
{"A % A :\t\t"}, {A} module (A), println
{"Etcetera...\n"}, println
exit(0)
</syntaxhighlight>
{{out}}
<pre>
'''ORIGINAL ARRAY :8,10,8,3,4,7,5,4,8,1'''
==========================================================================================
Increment : 9,11,9,4,5,8,6,5,9,2
Decrement : 8,10,8,3,4,7,5,4,8,1
post Increment: 8,10,8,3,4,7,5,4,8,1
9,11,9,4,5,8,6,5,9,2
post Decrement: 9,11,9,4,5,8,6,5,9,2
8,10,8,3,4,7,5,4,8,1
A + 5 : 13,15,13,8,9,12,10,9,13,6
5 + A : 13,15,13,8,9,12,10,9,13,6
A - 5 : 3,5,3,-2,-1,2,0,-1,3,-4
5 - A : -3,-5,-3,2,1,-2,0,1,-3,4
A * 5 : 40,50,40,15,20,35,25,20,40,5
5 * A : 40,50,40,15,20,35,25,20,40,5
A / 5 : 1.6,2,1.6,0.6,0.8,1.4,1,0.8,1.6,0.2
5 / A : 0.625,0.5,0.625,1.66667,1.25,0.714286,1,1.25,0.625,5
A \ 5 : 1,2,1,0,0,1,1,0,1,0
5 \ A : 0,0,0,1,1,0,1,1,0,5
A ^ 5 : 32768,100000,32768,243,1024,16807,3125,1024,32768,1
5 ^ A : 390625,9.76562e+06,390625,125,625,78125,3125,625,390625,5
A % 5 : 3,0,3,3,4,2,0,4,3,1
5 % A : 5,5,5,2,1,5,0,1,5,0
SQRT(A) + 5: 7.82843,8.16228,7.82843,6.73205,7,7.64575,7.23607,7,7.82843,6
--> CEIL : 8,9,8,7,7,8,8,7,8,6
--> FLOOR : 7,8,7,6,7,7,7,7,7,6
A + A : 16,20,16,6,8,14,10,8,16,2
A - A : 0,0,0,0,0,0,0,0,0,0
A * A : 64,100,64,9,16,49,25,16,64,1
A / A : 1,1,1,1,1,1,1,1,1,1
A \ A : 1,1,1,1,1,1,1,1,1,1
A ^ A : 1.67772e+07,1e+10,1.67772e+07,27,256,823543,3125,256,1.67772e+07,1
A % A : 0,0,0,0,0,0,0,0,0,0
Etcetera...
</pre>
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">ElementWise(M, operation, Val){
A := Obj_Copy(M),
for r, obj in A
for c, v in obj {
V := IsObject(Val) ? Val[r, c] : Val
switch, operation {
case "+": A[r, c] := A[r, c] + V
case "-": A[r, c] := A[r, c] - V
case "*": A[r, c] := A[r, c] * V
case "/": A[r, c] := A[r, c] / V
case "Mod": A[r, c] := Mod(A[r, c], V)
case "^": A[r, c] := A[r, c] ** V
}
}
return A
}</syntaxhighlight>
Examples:<syntaxhighlight lang="autohotkey">
M := [[1, 2, 3]
, [4, 5, 6]
, [7, 8, 9]]
output := "M`t=`t" obj2str(M) "`n"
output .= "M + 2`t=`t" obj2str(ElementWise(M, "+", 2)) "`n"
output .= "M - 2`t=`t" obj2str(ElementWise(M, "-", 2)) "`n"
output .= "M * 2`t=`t" obj2str(ElementWise(M, "*", 2)) "`n"
output .= "M / 2`t=`t" obj2str(ElementWise(M, "/", 2)) "`n"
output .= "M Mod 2`t=`t" obj2str(ElementWise(M, "Mod", 2)) "`n"
output .= "M ^ 2`t=`t" obj2str(ElementWise(M, "^", 2)) "`n"
output .= "`n"
output .= "M + M`t=`t" obj2str(ElementWise(M, "+", M)) "`n"
output .= "M - M`t=`t" obj2str(ElementWise(M, "-", M)) "`n"
output .= "M * M`t=`t" obj2str(ElementWise(M, "*", M)) "`n"
output .= "M / M`t=`t" obj2str(ElementWise(M, "/", M)) "`n"
output .= "M Mod M`t=`t" obj2str(ElementWise(M, "Mod", M)) "`n"
output .= "M ^ M`t=`t" obj2str(ElementWise(M, "^", M)) "`n"
MsgBox % output
return
obj2str(A){
output := "["
for r, obj in A{
output .= "["
for c, v in obj
output .= v ", "
output := Trim(output, ", ") "], "
}
return output := Trim(output, ", ") "]"
}</syntaxhighlight>
{{out}}
<pre>M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
M + 2 = [[3, 4, 5], [6, 7, 8], [9, 10, 11]]
M - 2 = [[-1, 0, 1], [2, 3, 4], [5, 6, 7]]
M * 2 = [[2, 4, 6], [8, 10, 12], [14, 16, 18]]
M / 2 = [[0.5, 1, 1.5], [2, 2.5, 3], [3.5, 4, 4.5]]
M Mod 2 = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
M ^ 2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]]
M + M = [[2, 4, 6], [8, 10, 12], [14, 16, 18]]
M - M = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
M * M = [[1, 4, 9], [16, 25, 36], [49, 64, 81]]
M / M = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
M Mod M = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
M ^ M = [[1, 4, 27], [256, 3125, 46656], [823543, 16777216, 387420489]]</pre>
=={{header|BBC BASIC}}==
All except exponentiation (^) are native operations in BBC BASIC.
<
a() = 7, 8, 7, 4, 0, 9 : b() = 4, 5, 1, 6, 2, 1
Line 282 ⟶ 426:
a$ = LEFT$(LEFT$(a$)) + "]"
NEXT
= a$ + "]"</
{{out}}
<pre>
Line 300 ⟶ 444:
=={{header|C}}==
Matrices are 2D double arrays.
<
#define for_i for(i = 0; i < h; i++)
Line 313 ⟶ 457:
void eop_s_##name(_M a, double s, _M b, int w, int h) {double x;int i,j;\
for_i for_j {x = a[i][j]; b[i][j] = res;}}
OPS(mul, x*s);OPS(div, x/s);OPS(add, x+s);OPS(sub, x-s);OPS(pow, pow(x, s));</
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 400 ⟶ 544:
matrix.DoOperation((a, b) => b - a, 100).Print();
}
}</
{{out}}
<pre>
Line 416 ⟶ 560:
=={{header|C++}}==
<
#include <cmath>
#include <iostream>
Line 679 ⟶ 823:
test_matrix_scalar();
return 0;
}</
{{out}}
Line 719 ⟶ 863:
=={{header|Clojure}}==
This function is for vector matrices; for list matrices, change the (vector?) function to the (list?) function and remove all the (vec) functions.
<
(vec (repeat i1 (vec (repeat i2 value)))))
Line 726 ⟶ 870:
(vec (map #(vec (map f %1 %2)) mtx1 mtx2)))
(recur f (initial-mtx (count mtx2) (count (first mtx2)) mtx1) mtx2)
))</
The mtx1 argument can either be a matrix or scalar; the function will sort the difference.
=={{header|Common Lisp}}==
Element-wise matrix-matrix operations. Matrices are represented as 2D-arrays.
<
(let* ((len (array-total-size A))
(m (car (array-dimensions A)))
Line 749 ⟶ 893:
(defun m* (A B) (element-wise-matrix #'* A B))
(defun m/ (A B) (element-wise-matrix #'/ A B))
(defun m^ (A B) (element-wise-matrix #'expt A B))</
Elementwise scalar-matrix operations.
<
(let* ((len (array-total-size A))
(m (car (array-dimensions A)))
Line 770 ⟶ 914:
(defun .* (c A) (element-wise-scalar #'* A c))
(defun ./ (A c) (element-wise-scalar #'/ A c))
(defun .^ (A c) (element-wise-scalar #'expt A c))</
=={{header|D}}==
<
T[][] elementwise(string op, T, U)(in T[][] A, in U B) {
Line 787 ⟶ 931:
writefln("%s:\n[%([%(%d, %)],\n %)]]\n\n[%([%(%d, %)],\n %)]]\n",
op, elementwise!op(M, 2), elementwise!op(M, M));
}</
{{out}}
<pre>+:
Line 835 ⟶ 979:
This alternative version offers more guarantees, same output:
<
T[][] elementwise(string op, T, U)(in T[][] A, in U B)
Line 870 ⟶ 1,014:
writefln(matFormat, elementwise!op(matrix, matrix));
}
}</
=={{header|Excel}}==
===LAMBDA===
Excel arithmetic operators are automatically lifted over array / matrix (grid) arguments.
In the examples below we are assuming the following bindings in the work-book Name Manager:
(See [https://www.microsoft.com/en-us/research/blog/lambda-the-ultimatae-excel-worksheet-function/ LAMBDA: The ultimate Excel worksheet function])
{{Works with|Office 365 betas 2021}}
<syntaxhighlight lang="lisp">EVAL
=LAMBDA(s, EVALUATE(s))
matrix
={1,2,3;4,5,6;7,8,9}</syntaxhighlight>
{{Out}}
{| class="wikitable"
|-
|||style="text-align:right; font-family:serif; font-style:italic; font-size:120%;"|fx
! colspan="4" style="text-align:left; vertical-align: bottom; font-family:Arial, Helvetica, sans-serif !important;"|=EVAL(A2)
|- style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff;"
|
| A
| B
| C
| D
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 1
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 2
| style="text-align:right; font-weight:bold" | matrix + matrix
| style="text-align:right; background-color:#cbcefb" | 2
| style="text-align:right" | 4
| style="text-align:right" | 6
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 3
| style="font-weight:bold" |
| style="text-align:right" | 8
| style="text-align:right" | 10
| style="text-align:right" | 12
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 4
| style="font-weight:bold" |
| style="text-align:right" | 14
| style="text-align:right" | 16
| style="text-align:right" | 18
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 5
| style="font-weight:bold" |
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 6
| style="text-align:right; font-weight:bold" | matrix - matrix
| style="text-align:right" | 0
| style="text-align:right" | 0
| style="text-align:right" | 0
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 7
| style="font-weight:bold" |
| style="text-align:right" | 0
| style="text-align:right" | 0
| style="text-align:right" | 0
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 8
| style="font-weight:bold" |
| style="text-align:right" | 0
| style="text-align:right" | 0
| style="text-align:right" | 0
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 9
| style="font-weight:bold" |
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 10
| style="text-align:right; font-weight:bold" | matrix * matrix
| style="text-align:right" | 1
| style="text-align:right" | 4
| style="text-align:right" | 9
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 11
|
| style="text-align:right" | 16
| style="text-align:right" | 25
| style="text-align:right" | 36
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 12
|
| style="text-align:right" | 49
| style="text-align:right" | 64
| style="text-align:right" | 81
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 13
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 14
| style="text-align:right; font-weight:bold" | matrix / matrix
| style="text-align:right" | 1
| style="text-align:right" | 4
| style="text-align:right" | 9
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 15
|
| style="text-align:right" | 16
| style="text-align:right" | 25
| style="text-align:right" | 36
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 16
|
| style="text-align:right" | 49
| style="text-align:right" | 64
| style="text-align:right" | 81
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 17
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 18
| style="text-align:right; font-weight:bold" | matrix + {1,2,3}
| style="text-align:right" | 2
| style="text-align:right" | 4
| style="text-align:right" | 6
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 19
|
| style="text-align:right" | 5
| style="text-align:right" | 7
| style="text-align:right" | 9
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 20
|
| style="text-align:right" | 8
| style="text-align:right" | 10
| style="text-align:right" | 12
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 21
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 22
| style="text-align:right; font-weight:bold" | matrix - {1,2,3}
| style="text-align:right" | 0
| style="text-align:right" | 0
| style="text-align:right" | 0
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 23
|
| style="text-align:right" | 3
| style="text-align:right" | 3
| style="text-align:right" | 3
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 24
|
| style="text-align:right" | 6
| style="text-align:right" | 6
| style="text-align:right" | 6
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 25
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 26
| style="text-align:right; font-weight:bold" | matrix * {1,2,3}
| style="text-align:right" | 1
| style="text-align:right" | 4
| style="text-align:right" | 9
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 27
|
| style="text-align:right" | 4
| style="text-align:right" | 10
| style="text-align:right" | 18
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 28
|
| style="text-align:right" | 7
| style="text-align:right" | 16
| style="text-align:right" | 27
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 29
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 30
| style="text-align:right; font-weight:bold" | matrix / {1,2,3}
| style="text-align:right" | 1
| style="text-align:right" | 1
| style="text-align:right" | 1
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 31
|
| style="text-align:right" | 4
| style="text-align:right" | 2.5
| style="text-align:right" | 2
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 32
|
| style="text-align:right" | 7
| style="text-align:right" | 4
| style="text-align:right" | 3
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 33
|
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 34
| style="text-align:right; font-weight:bold" | matrix + 2
| style="text-align:right" | 3
| style="text-align:right" | 4
| style="text-align:right" | 5
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 35
| style="font-weight:bold" |
| style="text-align:right" | 6
| style="text-align:right" | 7
| style="text-align:right" | 8
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 36
| style="font-weight:bold" |
| style="text-align:right" | 9
| style="text-align:right" | 10
| style="text-align:right" | 11
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 37
| style="font-weight:bold" |
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 38
| style="text-align:right; font-weight:bold" | matrix - 1
| style="text-align:right" | 0
| style="text-align:right" | 1
| style="text-align:right" | 2
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 39
| style="font-weight:bold" |
| style="text-align:right" | 3
| style="text-align:right" | 4
| style="text-align:right" | 5
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 40
| style="font-weight:bold" |
| style="text-align:right" | 6
| style="text-align:right" | 7
| style="text-align:right" | 8
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 41
| style="font-weight:bold" |
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 42
| style="text-align:right; font-weight:bold" | matrix * 2
| style="text-align:right" | 2
| style="text-align:right" | 4
| style="text-align:right" | 6
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 43
| style="font-weight:bold" |
| style="text-align:right" | 8
| style="text-align:right" | 10
| style="text-align:right" | 12
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 44
| style="font-weight:bold" |
| style="text-align:right" | 14
| style="text-align:right" | 16
| style="text-align:right" | 18
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 45
| style="font-weight:bold" |
|
|
|
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 46
| style="text-align:right; font-weight:bold" | matrix / 2
| style="text-align:right" | 0.5
| style="text-align:right" | 1
| style="text-align:right" | 1.5
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 47
|
| style="text-align:right" | 2
| style="text-align:right" | 2.5
| style="text-align:right" | 3
|-
| style="text-align:center; font-family:Arial, Helvetica, sans-serif !important; background-color:#000000; color:#ffffff" | 48
|
| style="text-align:right" | 3.5
| style="text-align:right" | 4
| style="text-align:right" | 4.5
|}
=={{header|Factor}}==
The <code>math.matrices</code> vocabulary provides matrix-matrix and matrix-scalar arithmetic words. I wasn't able to find any for exponentiation, so I wrote them.
<
math.matrices math.vectors prettyprint sequences ;
Line 888 ⟶ 1,349:
{ { 1 2 } { 3 4 } } { { 5 6 } { 7 8 } } { m+ m- m* m/ m^ }
{ { -1 9 4 } { 5 -13 0 } } 3 { m+n m-n m*n m/n m^n }
[ show ] 3bi@</
{{out}}
<pre>
Line 907 ⟶ 1,368:
All element based operations are suported by default in Fortran(90+)
<syntaxhighlight lang="fortran">
program element_operations
implicit none
Line 969 ⟶ 1,430:
end program element_operations
</syntaxhighlight>
{{out}}
Line 1,009 ⟶ 1,470:
</pre>
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Dim Shared As Double a(1,2) = {{7, 8, 7}, {4, 0, 9}}
Dim Shared As Double b(1,2) = {{4, 5, 1}, {6, 2, 1}}
Dim Shared As Double c(1,2)
Dim Shared As Double fila, columna
Dim Shared As String p
Sub list(a() As Double)
p = "["
For fila = 0 To Ubound(a,1)
p &= "["
For columna = 0 To Ubound(b,2)
p &= Str(a(fila, columna)) + ", "
Next columna
p = Left(p,Len(p)-2) + "]"
Next fila
p &= "]"
Print p;
End Sub
REM Matrix-Matrix:
Sub Mostrarmm(a() As Double, op As String, b() As Double, c() As Double)
list(a()) : Print " "; op; " "; : list(b()) : Print " = "; : list(c()) : Print
End Sub
Sub addmm(a() As Double, b() As Double, c() As Double)
REM adición
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(b,2) To Ubound(b,2)
c(fila, columna) = a(fila,columna) + b(fila,columna)
Next columna
Next fila
End Sub
Sub resmm(a() As Double, b() As Double, c() As Double)
REM sustracción
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(b,2) To Ubound(b,2)
c(fila, columna) = a(fila,columna) - b(fila,columna)
Next columna
Next fila
End Sub
Sub mulmm(a() As Double, b() As Double, c() As Double)
REM multiplicación
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(b,2) To Ubound(b,2)
c(fila, columna) = a(fila,columna) * b(fila,columna)
Next columna
Next fila
End Sub
Sub divmm(a() As Double, b() As Double, c() As Double)
REM división
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(b,2) To Ubound(b,2)
c(fila, columna) = a(fila,columna) / b(fila,columna)
Next columna
Next fila
End Sub
Sub powmm(a() As Double, b() As Double, c() As Double)
REM exponenciación
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(b,2) To Ubound(b,2)
c(fila, columna) = a(fila,columna) ^ b(fila,columna)
Next columna
Next fila
End Sub
REM Matrix-Scalar:
Sub Mostrarms(a() As Double, op As String, b As Double, c() As Double)
list(a()) : Print " "; op; " "; Str(b); " = "; : list(c()) : Print
End Sub
Sub addms(a() As Double, b As Double, c() As Double)
REM adición
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(a,2) To Ubound(a,2)
c(fila, columna) = a(fila,columna) + b
Next columna
Next fila
End Sub
Sub resms(a() As Double, b As Double, c() As Double)
REM sustracción
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(a,2) To Ubound(a,2)
c(fila, columna) = a(fila,columna) - b
Next columna
Next fila
End Sub
Sub mulms(a() As Double, b As Double, c() As Double)
REM multiplicación
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(a,2) To Ubound(a,2)
c(fila, columna) = a(fila,columna) * b
Next columna
Next fila
End Sub
Sub divms(a() As Double, b As Double, c() As Double)
REM división
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(a,2) To Ubound(a,2)
c(fila, columna) = a(fila,columna) / b
Next columna
Next fila
End Sub
Sub powms(a() As Double, b As Double, c() As Double)
REM exponenciación
For fila = Lbound(a,1) To Ubound(a,1)
For columna = Lbound(a,2) To Ubound(a,2)
c(fila, columna) = a(fila,columna) ^ b
Next columna
Next fila
End Sub
REM Matrix-Matrix:
addmm(a(), b(), c()) : Mostrarmm(a(), "+", b(), c())
resmm(a(), b(), c()) : Mostrarmm(a(), "-", b(), c())
mulmm(a(), b(), c()) : Mostrarmm(a(), "*", b(), c())
divmm(a(), b(), c()) : Mostrarmm(a(), "/", b(), c())
powmm(a(), b(), c()) : Mostrarmm(a(), "^", b(), c())
Print
REM Matrix-Scalar:
addms(a(), 3, c()) : Mostrarms(a(), "+", 3, c())
resms(a(), 3, c()) : Mostrarms(a(), "-", 3, c())
mulms(a(), 3, c()) : Mostrarms(a(), "*", 3, c())
divms(a(), 3, c()) : Mostrarms(a(), "/", 3, c())
powms(a(), 3, c()) : Mostrarms(a(), "^", 3, c())
Sleep</syntaxhighlight>
{{out}}
<pre>[[7, 8, 7][4, 0, 9]] + [[4, 5, 1][6, 2, 1]] = [[11, 13, 8][10, 2, 10]]
[[7, 8, 7][4, 0, 9]] - [[4, 5, 1][6, 2, 1]] = [[3, 3, 6][-2, -2, 8]]
[[7, 8, 7][4, 0, 9]] * [[4, 5, 1][6, 2, 1]] = [[28, 40, 7][24, 0, 9]]
[[7, 8, 7][4, 0, 9]] / [[4, 5, 1][6, 2, 1]] = [[1.75, 1.6, 7][0.6666666666666666, 0, 9]]
[[7, 8, 7][4, 0, 9]] ^ [[4, 5, 1][6, 2, 1]] = [[2401, 32768, 7][4096, 0, 9]]
[[7, 8, 7][4, 0, 9]] + 3 = [[10, 11, 10][7, 3, 12]]
[[7, 8, 7][4, 0, 9]] - 3 = [[4, 5, 4][1, -3, 6]]
[[7, 8, 7][4, 0, 9]] * 3 = [[21, 24, 21][12, 0, 27]]
[[7, 8, 7][4, 0, 9]] / 3 = [[2.333333333333334, 2.666666666666667, 2.333333333333334][1.333333333333333, 0, 3]]
[[7, 8, 7][4, 0, 9]] ^ 3 = [[343, 512, 343][64, 0, 729]]</pre>
=={{header|Go}}==
A package, which can be referred to in other, higher-order tasks.
<
import (
Line 1,081 ⟶ 1,691:
func MulScalar(m Matrix, s float64) Matrix { return elementWiseMS(m, s, mul) }
func DivScalar(m Matrix, s float64) Matrix { return elementWiseMS(m, s, div) }
func ExpScalar(m Matrix, s float64) Matrix { return elementWiseMS(m, s, exp) }</
Package use:
<
import (
Line 1,115 ⟶ 1,725:
h("m1 / s:", element.DivScalar(m1, s))
h("m1 ^ s:", element.ExpScalar(m1, s))
}</
{{out}}
<pre>
Line 1,161 ⟶ 1,771:
=={{header|Groovy}}==
Solution:
<
List<List<Number>> contents = []
Line 1,227 ⟶ 1,837:
contents.hashCode()
}
}</
The following ''NaiveMatrixCategory'' class allows for modification of regular ''Number'' behavior when interacting with ''NaiveMatrix''.
<
class NaiveMatrixCategory {
Line 1,244 ⟶ 1,854:
: DefaultGroovyMethods.asType(a, type)
}
}</
Test:
<
println 'Demo 1: functionality as requested'
Line 1,278 ⟶ 1,888:
println "a / 2 == (${a}) / 2 == " + (a / 2)
println "a ** 2 == (${a}) ** 2 == " + (a ** 2)
println "a % 2 == (${a}) % 2 == " + (a % 2)</
Output:
<pre>Demo 1: functionality as requested
Line 1,309 ⟶ 1,919:
=={{header|Haskell}}==
Matrices are represented here as Immutable Arrays.
<
{-# LANGUAGE RankNTypes #-}
Line 1,437 ⟶ 2,047:
print $ m1 **. s
putStrLn "m1 ^^ s"
print $ m1 ^^. s</
{{out}}
<pre>m1
Line 1,484 ⟶ 2,094:
It would be easy to replace this with another construct to produce a version that works in both languages.
The output flattens each displayed matrix onto a single line to save space here.
<
a := [[1,2,3],[4,5,6],[7,8,9]]
b := [[9,8,7],[6,5,4],[3,2,1]]
Line 1,520 ⟶ 2,130:
procedure showMat(label, m)
every writes(label | right(!!m,5) | "\n")
end</
{{out}}
Line 1,541 ⟶ 2,151:
=={{header|J}}==
'''Solution''': J's arithmetical primitives act elementwise by default (in J parlance, such operations are known as "scalar" or "rank zero", which means they generalize to high-order arrays transparently, operating elementwise). Thus: <
vector =: 2 3 5
matrix =: 3 3 $ 7 11 13 17 19 23 29 31 37
Line 1,564 ⟶ 2,174:
49 121 169
289 361 529
841 961 1369</
Note that in some branches of mathematics, it has been traditional to define multiplication such that it is not performed element-wise. This can introduce some complications ([[wp:Einstein notation]] is arguably the best approach for resolving those complexities in latex, when they occur frequently enough that mentioning and using the notation is not more complicated than explicitly describing the multiply-and-sum) and makes expressing element-wise multiplication complicated. J deals with this conflict by making its multiplication primitive be elementwise (consistent with the rest of the language) and by using a different verb (typically +/ .*) to represent the traditional non-element-wise multiply and sum operation.
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.util.Arrays;
import java.util.HashMap;
Line 1,629 ⟶ 2,239:
}
}
</syntaxhighlight>
=={{header|jq}}==
Line 1,653 ⟶ 2,263:
'''Part 1'''
<
# and occurrences of .[1] will refer to the corresponding element in other.
def elementwise( operator; other ):
Line 1,664 ⟶ 2,274:
([]; reduce range(0; $cols) as $j
(.; .[$i][$j] = ([$self[$i][$j], $other[$i][$j]] | operator) ) )
end ;</
'''Example''':
<
| ( ($m1|elementwise(.[0] + .[1]; $m2) ),
($m1|elementwise(.[0] + 2 * .[1]; $m2) ),
($m1|elementwise(.[0] < .[1]; $m2) ) )
</syntaxhighlight>
{{Out}}
<
[[7,15,6],[17,9,13]]
[[false,true,false],[true,false,false]]
</syntaxhighlight>
'''Part 2'''
Line 1,686 ⟶ 2,296:
polymorphic. For example, + is defined on strings and other types
besides numbers.
<
def pow(i): . as $in | reduce range(0;i) as $i (1; .*$in);
def operation(x; op; y):
Line 1,708 ⟶ 2,318:
([]; reduce range(0; $cols) as $j
(.; .[$i][$j] = operation($self[$i][$j]; operator; $other[$i][$j] ) ) )
end;</
'''Example''':
<
| ( ($m1|elementwise2("+"; $m2) ),
($m1|elementwise2("//"; $m2)),
($m1|elementwise2(.[0] < .[1]; $m2) ) )</
{{Out}}
<
[[1,0,4],[0,2,4]]
[[false,true,false],[true,false,false]]
</syntaxhighlight>
=={{header|Julia}}==
In Julia operations with `.` before are for convention Element-wise:
<
@show [1 2 3; 2 1 2] .+ 1
@show [1 2 3; 2 2 1] .- [1 1 1; 2 1 0]
Line 1,728 ⟶ 2,338:
@show [1 2 3; 3 2 1] .* 2
@show [9 8 6; 3 2 3] ./ [3 1 2; 2 1 2]
@show [3 2 2; 1 2 3] .^ [1 2 3; 2 1 2]</
{{out}}
Line 1,742 ⟶ 2,352:
{{trans|J}}
<
vector: 2 3 5
matrix: 3 3 # 7 11 13 17 19 23 29 31 37
Line 1,766 ⟶ 2,376:
289 361 529
841 961 1369)
</
=={{header|Kotlin}}==
<
typealias Matrix = Array<DoubleArray>
Line 1,816 ⟶ 2,426:
println("s = $s:\n")
for ((i, op) in ops.withIndex()) m.elementwiseOp(s, op).print(names[i], true)
}</
{{out}}
Line 1,879 ⟶ 2,489:
=={{header|Maple}}==
<
#addition
Line 1,894 ⟶ 2,504:
#exponentiation
<1,2,0; 7,2,7; 6,11,3>^~5;</
{{Out|Output}}
<pre>
Line 1,905 ⟶ 2,515:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
M + S
M - S
Line 1,936 ⟶ 2,546:
20880467999847912034355032910567}, {2567686153161211134561828214731016126483469,
17069174130723235958610643029059314756044734431,
10555134955777783414078330085995832946127396083370199442517}}</
=={{header|MATLAB}}==
<
b = rand(10,10);
scalar_matrix = a * b;
component_wise = b .* b;</
=={{header|Maxima}}==
<
b: matrix([2, 4], [3, 1]);
Line 1,956 ⟶ 2,566:
a^b; /* won't work */
fullmapl("^", a, b);
sin(a);</
=={{header|Nim}}==
<
type Matrix[height, width: static Positive; T: SomeNumber] = array[height, array[width, T]]
Line 2,151 ⟶ 2,761:
echo pow(mfloat1, 2.0)
echo "pow(2.0, m1)"
echo pow(2.0, mfloat1)</
{{out}}
Line 2,247 ⟶ 2,857:
=={{header|PARI/GP}}==
GP already implements element-wise matrix-matrix addition and subtraction and element-wise scalar-matrix multiplication and division. Other element-wise matrix-matrix functions:
<
divMM(A,B)=matrix(#A[,1],#A,i,j,A[i,j]/B[i,j]);
powMM(A,B)=matrix(#A[,1],#A,i,j,A[i,j]^B[i,j]);</
Other element-wise scalar-matrix functions:
<
subMs(A,s)=A-matrix(#A[,1],#A,i,j,s);
powMs(A,s)=matrix(#A[,1],#A,i,j,A[i,j]^s);</
PARI implements convenience functions <code>vecmul</code> (element-wise matrix-matrix multiplication), <code>vecdiv</code> (element-wise matrix-matrix division), and <code>vecpow</code> (element-wise matrix-scalar exponentiation), as well as <code>vecmodii</code> and <code>vecinv</code>. These operate on vectors, but a <code>t_MAT</code> is simply an array of vectors in PARI so it applies fairly easily.
Line 2,263 ⟶ 2,873:
This example demonstrates Perl's operator overload ability and bulk list operations using <tt>map</tt>.
<syntaxhighlight lang="perl">use v5.36;
use overload
'
'
'
'
'
sub new ($class, $value) { bless $value, ref $class || $class }
sub add { ref($_[1]) ? [map { $_[0][$_] + $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] + $_[1] } 0 .. $#{$_[0]} ] }
sub sub { ref($_[1]) ? [map { $_[0][$_] - $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] - $_[1] } 0 .. $#{$_[0]} ] }
sub mul { ref($_[1]) ? [map { $_[0][$_] * $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] * $_[1] } 0 .. $#{$_[0]} ] }
sub div { ref($_[1]) ? [map { $_[0][$_] / $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] / $_[1] } 0 .. $#{$_[0]} ] }
sub exp { ref($_[1]) ? [map { $_[0][$_] ** $_[1][$_] } 0 .. $#{$_[0]} ] : [map { $_[0][$_] ** $_[1] } 0 .. $#{$_[0]} ] }
package main;
$a = Elementwise->new([<1 2 3 4 5 6 7 8 9>]);
say <<"END";
a @$a
a OP a
+ @{$a+$a}
Line 2,314 ⟶ 2,904:
* @{$a*$a}
/ @{$a/$a}
a OP 5
+ @{$a+5}
Line 2,320 ⟶ 2,911:
* @{$a*5}
/ @{$a/5}
END</syntaxhighlight>
{{out}}
<pre>a 1 2 3 4 5 6 7 8 9
a OP a
+ 2 4 6 8 10 12 14 16 18
Line 2,330 ⟶ 2,922:
* 1 4 9 16 25 36 49 64 81
/ 1 1 1 1 1 1 1 1 1
a OP 5
+ 6 7 8 9 10 11 12 13 14
Line 2,336 ⟶ 2,929:
* 5 10 15 20 25 30 35 40 45
/ 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8
=={{header|Phix}}==
{{libheader|Phix/basics}}
Phix has builtin sequence ops, which work fine with a multi-dimensional array / matrix:
<!--<
<span style="color: #008080;">constant</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span
<span style="color: #000000;">m2</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span
<span style="color: #0000FF;">?{</span
<span style="color: #0000FF;">?{</span
<span style="color: #0000FF;">?{</span
<span style="color: #0000FF;">?{</span
<span style="color: #0000FF;">?{</span
<span style="color: #0000FF;">?{</span
<span style="color: #0000FF;">?{</span
<span style="color: #0000FF;">?{</span
<span style="color: #0000FF;">?{</span
<span style="color: #0000FF;">?{</span
<!--</
{{out}}
<pre>
Line 2,370 ⟶ 2,963:
=={{header|PicoLisp}}==
<
(mapcar '((L1 L2) (mapcar Fun L1 L2)) Mat1 Mat2) )
(de elementWiseScalar (Fun Mat Scalar)
(elementWiseMatrix Fun Mat (circ (circ Scalar))) )</
Test:
<pre>(let (S 10 M '((7 11 13) (17 19 23) (29 31 37)))
Line 2,404 ⟶ 2,997:
Any arithmetic operation can be applied to elements of arrays.
These examples illustrate element-by-element multiplication, but addition, subtraction, division, and exponentiation can also be written.
<
declare (m(3,3), v(3) fixed;
Line 2,412 ⟶ 3,005:
v = scalar * vector;
v = vector * vector;</
=={{header|Python}}==
<
>>> from operator import add, sub, mul, floordiv
>>> from pprint import pprint as pp
Line 2,457 ⟶ 3,050:
pow : [[10000000, 100000000, 10000000, 10000], [10000, 1000000000, 10000, 10], [100, 1000, 1000000, 10000]]
<lambda> : [[13, 12, 13, 16], [16, 11, 16, 19], [18, 17, 14, 16]]
>>> </
=={{header|R}}==
Line 2,463 ⟶ 3,056:
In R most operations work on vectors and matrices:
<
mat <- matrix(1:4, 2, 2)
Line 2,474 ⟶ 3,067:
mat + mat
mat * mat
mat ^ mat</
{{out}}
Line 2,514 ⟶ 3,107:
=={{header|Racket}}==
{{trans|R}}
<
(define mat (list->array #(2 2) '(1 3 2 4)))
Line 2,526 ⟶ 3,119:
(array* mat mat)
(array-map expt mat mat)
</syntaxhighlight>
{{out}}
Line 2,541 ⟶ 3,134:
=={{header|Raku}}==
(formerly Perl 6)
Raku already implements this and other metaoperators as higher-order functions (cross, zip, reduce, triangle, etc.) that are usually accessed through a meta-operator syntactic sugar that is productive over all appropriate operators, including user-defined ones. In this case, a dwimmy element-wise operator (generically known as a "hyper") is indicated by surrounding the operator with double angle quotes. Hypers dwim on the pointy end with cyclic APL semantics as necessary. You can turn the quote the other way to suppress dwimmery on that end. In this case we could have used <tt>»op»</tt> instead of <tt>«op»</tt> since the short side is always on the right.
<syntaxhighlight lang="raku"
[1,2,3],
[4,5,6],
Line 2,549 ⟶ 3,141:
sub msay(@x) {
say .map( { ($_%1) ?? $_.nude.join('/') !! $_ } ).join(' ') for @x;
say '';
}
Line 2,576 ⟶ 3,165:
msay @a M+ [1,2,3];
msay @a M+ 2;
</syntaxhighlight>
{{out}}
<pre> 2 4 6
Line 2,640 ⟶ 3,229:
=={{header|REXX}}==
===discrete===
<
m= (1 2 3) (4 5 6) (7 8 9)
w= words(m); do
end /*rows*/
cols= rows
call showMat M, 'M matrix'
answer= matAdd(m, 2 );
answer= matSub(m, 7 );
answer= matMul(m, 2.5);
answer= matPow(m, 3 );
answer= matDiv(m, 4 );
answer= matIdv(m, 2 );
answer= matMod(m, 3 );
exit
/*──────────────────────────────────────────────────────────────────────────────────────*/
matAdd: parse arg @,#; call mat#;
matSub: parse arg @,#; call mat#;
matMul: parse arg @,#; call mat#;
matDiv: parse arg @,#; call mat#;
matIdv: parse arg @,#; call mat#;
matPow: parse arg @,#; call mat#;
matMod: parse arg @,#; call mat#;
mat#: w= words(@);
mat@: @= !.1;
/*──────────────────────────────────────────────────────────────────────────────────────*/
showMat: parse arg @, hdr; L= 0; say
say center(hdr, max( length(hdr)+4, cols * (L+1)+4), "─")
n= 0
return</
{{out|output|text= when using the internal default input:}}
<pre style="height:
──M matrix──
1 2 3
Line 2,715 ⟶ 3,306:
===generalized===
<
m= (1 2 3) (4 5 6) (7 8 9)
w= words(m); do
end /*k*/; cols= rows
call showMat M, 'M matrix'
ans= matOp(m, '+2' ); call showMat ans, "M matrix, added 2"
ans= matOp(m, '-7' ); call showMat ans, "M matrix, subtracted 7"
ans= matOp(m, '*2.5' ); call showMat ans, "M matrix, multiplied by 2½"
ans= matOp(m, '**3' ); call showMat ans, "M matrix, cubed"
ans= matOp(m, '/4' ); call showMat ans, "M matrix, divided by 4"
ans= matOp(m, '%2' ); call showMat ans, "M matrix, integer halved"
ans= matOp(m, '//3' ); call showMat ans, "M matrix, modulus 3"
ans= matOp(m, '*3-1' ); call showMat ans, "M matrix, tripled, less one"
exit
/*──────────────────────────────────────────────────────────────────────────────────────*/
matOp:
mat#:
mat@:
/*──────────────────────────────────────────────────────────────────────────────────────*/
showMat: parse arg @, hdr; L= 0; say
say; say center(hdr,max(length(hdr)+4,cols*(L+1)+4),"─")
n= 0
return</
{{out|output|text= when using the internal default input:}}
<pre style="height:
──M matrix──
1 2 3
Line 2,798 ⟶ 3,390:
=={{header|Ruby}}==
<
class Matrix
Line 2,813 ⟶ 3,405:
[:+, :-, :*, :/, :fdiv, :**, :%].each do |op|
puts "m1 %-4s m2 = %s" % [op, m1.element_wise(op, m2)]
end</
{{out}}
<pre>
Line 2,829 ⟶ 3,421:
=={{header|Rust}}==
<
elements: Vec<f32>,
pub height: u32,
Line 2,963 ⟶ 3,555:
// | 15 |
matrix_multiplication(&matrix1, &matrix3).unwrap().print();
}</
=={{header|Sidef}}==
The built-in metaoperators `~W<op>`, `~S<op>` and `~RS<op>` are defined for arbitrary nested arrays.
<
var m2 = [[2,7,1],[8,2,2]]
Line 2,991 ⟶ 3,583:
say (m1 ~RS/ 42)
say (m1 ~RS** 10)
# ...</
{{out}}
<pre>
Line 3,017 ⟶ 3,609:
=={{header|Standard ML}}==
<
local
open Array2
Line 3,047 ⟶ 3,639:
List.map toList [m1+m2, m1-m2, m1*m2,
m1 splus s, m1 sminus s, m1 stimes s]
end;</
'''Output:'''
<
[[[5,5],[5,5]],[[~3,~1],[1,3]],[[4,6],[6,4]],[[3,4],[5,6]],[[~1,0],[1,2]],
[[2,4],[6,8]]] : int list list list</
=={{header|Stata}}==
<
a = rnormal(5,5,0,1)
b = 2
Line 3,071 ⟶ 3,663:
a:/b
a:^b
end</
=={{header|Tcl}}==
<
proc alias {name args} {uplevel 1 [list interp alias {} $name {} {*}$args]}
Line 3,113 ⟶ 3,705:
alias .* elementwiseMatSca {{a b} {expr {$a*$b}}}
alias ./ elementwiseMatSca {{a b} {expr {$a/$b}}}
alias .** elementwiseMatSca {{a b} {expr {$a**$b}}}</
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import math
struct Matrix {
mut:
ele []f64
stride int
}
fn matrix_from_rows(rows [][]f64) Matrix {
if rows.len == 0 {
return Matrix{[], 0}
}
mut m := Matrix{[]f64{len: rows.len*rows[0].len}, rows[0].len}
for rx, row in rows {
m.ele = m.ele[..rx*m.stride]
m.ele << row
m.ele << m.ele[(rx+1)*m.stride..]
}
return m
}
fn like(m Matrix) Matrix {
return Matrix{[]f64{len: m.ele.len}, m.stride}
}
fn (m Matrix) str() string {
mut s := ""
for e := 0; e < m.ele.len; e += m.stride {
s += "${m.ele[e..e+m.stride]} \n"
}
return s
}
type BinaryFunc64 = fn(f64, f64) f64
fn element_wise_mm(m1 Matrix, m2 Matrix, f BinaryFunc64) Matrix {
mut z := like(m1)
for i, m1e in m1.ele {
z.ele[i] = f(m1e, m2.ele[i])
}
return z
}
fn element_wise_ms(m Matrix, s f64, f BinaryFunc64) Matrix {
mut z := like(m)
for i, e in m.ele {
z.ele[i] = f(e, s)
}
return z
}
fn add(a f64, b f64) f64 { return a + b }
fn sub(a f64, b f64) f64 { return a - b }
fn mul(a f64, b f64) f64 { return a * b }
fn div(a f64, b f64) f64 { return a / b }
fn exp(a f64, b f64) f64 { return math.pow(a, b) }
fn add_matrix(m1 Matrix, m2 Matrix) Matrix { return element_wise_mm(m1, m2, add) }
fn sub_matrix(m1 Matrix, m2 Matrix) Matrix { return element_wise_mm(m1, m2, sub) }
fn mul_matrix(m1 Matrix, m2 Matrix) Matrix { return element_wise_mm(m1, m2, mul) }
fn div_matrix(m1 Matrix, m2 Matrix) Matrix { return element_wise_mm(m1, m2, div) }
fn exp_matrix(m1 Matrix, m2 Matrix) Matrix { return element_wise_mm(m1, m2, exp) }
fn add_scalar(m Matrix, s f64) Matrix { return element_wise_ms(m, s, add) }
fn sub_scalar(m Matrix, s f64) Matrix { return element_wise_ms(m, s, sub) }
fn mul_scalar(m Matrix, s f64) Matrix { return element_wise_ms(m, s, mul) }
fn div_scalar(m Matrix, s f64) Matrix { return element_wise_ms(m, s, div) }
fn exp_scalar(m Matrix, s f64) Matrix { return element_wise_ms(m, s, exp) }
fn h(heading string, m Matrix) {
println(heading)
print(m)
}
fn main() {
m1 := matrix_from_rows([[f64(3), 1, 4], [f64(1), 5, 9]])
m2 := matrix_from_rows([[f64(2), 7, 1], [f64(8), 2, 8]])
h("m1:", m1)
h("m2:", m2)
println('')
h("m1 + m2:", add_matrix(m1, m2))
h("m1 - m2:", sub_matrix(m1, m2))
h("m1 * m2:", mul_matrix(m1, m2))
h("m1 / m2:", div_matrix(m1, m2))
h("m1 ^ m2:", exp_matrix(m1, m2))
println('')
s := .5
println("s: $s")
h("m1 + s:", add_scalar(m1, s))
h("m1 - s:", sub_scalar(m1, s))
h("m1 * s:", mul_scalar(m1, s))
h("m1 / s:", div_scalar(m1, s))
h("m1 ^ s:", exp_scalar(m1, s))
}</syntaxhighlight>
{{out}}
<pre>
m1:
[3, 1, 4]
[1, 5, 9]
m2:
[2, 7, 1]
[8, 2, 8]
m1 + m2:
[5, 8, 5]
[9, 7, 17]
m1 - m2:
[1, -6, 3]
[-7, 3, 1]
m1 * m2:
[6, 7, 4]
[8, 10, 72]
m1 / m2:
[1.5, 0.14285714285714285, 4]
[0.125, 2.5, 1.125]
m1 ^ m2:
[9, 1, 4]
[1, 25, 4.3046721e+07]
s: 0.5
m1 + s:
[3.5, 1.5, 4.5]
[1.5, 5.5, 9.5]
m1 - s:
[2.5, 0.5, 3.5]
[0.5, 4.5, 8.5]
m1 * s:
[1.5, 0.5, 2]
[0.5, 2.5, 4.5]
m1 / s:
[6, 2, 8]
[2, 10, 18]
m1 ^ s:
[1.7320508075688772, 1, 2]
[1, 2.23606797749979, 3]
</pre>
=={{header|Wren}}==
Line 3,121 ⟶ 3,853:
However, to avoid creating a real hodgepodge, we simply define methods for all the required operations whilst deferring to existing operations where appropriate.
<
import "./matrix" for Matrix
// matrix-matrix element wise ops
Line 3,225 ⟶ 3,957:
Fmt.mprint(SM.div(s, m), 8, 6)
System.print("\ns ^ m:")
Fmt.mprint(SM.pow(s, m), 3, 0)</
{{out}}
Line 3,313 ⟶ 4,045:
=={{header|zkl}}==
<
M:=GSL.Matrix(3,3).set(3,5,7, 1,2,3, 2,4,6);
x:=2;
Line 3,324 ⟶ 4,056:
}
mSqrd:=M.pump(0,M.copy(),fcn(x){ x*x }); // M element by element
println("M square elements:\n%s\n".fmt(mSqrd.format()));</
{{out}}
<pre>
|