Element-wise operations: Difference between revisions
m
→{{header|Wren}}: Minor tidy
mNo edit summary |
m (→{{header|Wren}}: Minor tidy) |
||
(6 intermediate revisions by 4 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 228:
</pre>
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
#include <hopper.h>
Line 270:
{"Etcetera...\n"}, println
exit(0)
</syntaxhighlight>
{{out}}
<pre>
Line 309:
=={{header|AutoHotkey}}==
<
A := Obj_Copy(M),
for r, obj in A
Line 324:
}
return A
}</
Examples:<
M := [[1, 2, 3]
, [4, 5, 6]
Line 355:
}
return output := Trim(output, ", ") "]"
}</
{{out}}
<pre>M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Line 374:
=={{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 426:
a$ = LEFT$(LEFT$(a$)) + "]"
NEXT
= a$ + "]"</
{{out}}
<pre>
Line 444:
=={{header|C}}==
Matrices are 2D double arrays.
<
#define for_i for(i = 0; i < h; i++)
Line 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 544:
matrix.DoOperation((a, b) => b - a, 100).Print();
}
}</
{{out}}
<pre>
Line 560:
=={{header|C++}}==
<
#include <cmath>
#include <iostream>
Line 823:
test_matrix_scalar();
return 0;
}</
{{out}}
Line 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 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 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 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 931:
writefln("%s:\n[%([%(%d, %)],\n %)]]\n\n[%([%(%d, %)],\n %)]]\n",
op, elementwise!op(M, 2), elementwise!op(M, M));
}</
{{out}}
<pre>+:
Line 979:
This alternative version offers more guarantees, same output:
<
T[][] elementwise(string op, T, U)(in T[][] A, in U B)
Line 1,014:
writefln(matFormat, elementwise!op(matrix, matrix));
}
}</
=={{header|Excel}}==
Line 1,026:
{{Works with|Office 365 betas 2021}}
<
=LAMBDA(s, EVALUATE(s))
matrix
={1,2,3;4,5,6;7,8,9}</
{{Out}}
{| class="wikitable"
Line 1,335:
=={{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 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 1,368:
All element based operations are suported by default in Fortran(90+)
<syntaxhighlight lang="fortran">
program element_operations
implicit none
Line 1,430:
end program element_operations
</syntaxhighlight>
{{out}}
Line 1,473:
=={{header|FreeBASIC}}==
<
Dim Shared As Double b(1,2) = {{4, 5, 1}, {6, 2, 1}}
Dim Shared As Double c(1,2)
Line 1,605:
divms(a(), 3, c()) : Mostrarms(a(), "/", 3, c())
powms(a(), 3, c()) : Mostrarms(a(), "^", 3, c())
Sleep</
{{out}}
<pre>[[7, 8, 7][4, 0, 9]] + [[4, 5, 1][6, 2, 1]] = [[11, 13, 8][10, 2, 10]]
Line 1,622:
=={{header|Go}}==
A package, which can be referred to in other, higher-order tasks.
<
import (
Line 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,725:
h("m1 / s:", element.DivScalar(m1, s))
h("m1 ^ s:", element.ExpScalar(m1, s))
}</
{{out}}
<pre>
Line 1,771:
=={{header|Groovy}}==
Solution:
<
List<List<Number>> contents = []
Line 1,837:
contents.hashCode()
}
}</
The following ''NaiveMatrixCategory'' class allows for modification of regular ''Number'' behavior when interacting with ''NaiveMatrix''.
<
class NaiveMatrixCategory {
Line 1,854:
: DefaultGroovyMethods.asType(a, type)
}
}</
Test:
<
println 'Demo 1: functionality as requested'
Line 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,919:
=={{header|Haskell}}==
Matrices are represented here as Immutable Arrays.
<
{-# LANGUAGE RankNTypes #-}
Line 2,047:
print $ m1 **. s
putStrLn "m1 ^^ s"
print $ m1 ^^. s</
{{out}}
<pre>m1
Line 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 2,130:
procedure showMat(label, m)
every writes(label | right(!!m,5) | "\n")
end</
{{out}}
Line 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 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 2,239:
}
}
</syntaxhighlight>
=={{header|jq}}==
Line 2,263:
'''Part 1'''
<
# and occurrences of .[1] will refer to the corresponding element in other.
def elementwise( operator; other ):
Line 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 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 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 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 2,352:
{{trans|J}}
<
vector: 2 3 5
matrix: 3 3 # 7 11 13 17 19 23 29 31 37
Line 2,376:
289 361 529
841 961 1369)
</
=={{header|Kotlin}}==
<
typealias Matrix = Array<DoubleArray>
Line 2,426:
println("s = $s:\n")
for ((i, op) in ops.withIndex()) m.elementwiseOp(s, op).print(names[i], true)
}</
{{out}}
Line 2,489:
=={{header|Maple}}==
<
#addition
Line 2,504:
#exponentiation
<1,2,0; 7,2,7; 6,11,3>^~5;</
{{Out|Output}}
<pre>
Line 2,515:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
M + S
M - S
Line 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 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,761:
echo pow(mfloat1, 2.0)
echo "pow(2.0, m1)"
echo pow(2.0, mfloat1)</
{{out}}
Line 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,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,924 ⟶ 2,904:
* @{$a*$a}
/ @{$a/$a}
a OP 5
+ @{$a+5}
Line 2,930 ⟶ 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,940 ⟶ 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,946 ⟶ 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;">7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">9</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: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">}}</span>
Line 2,964 ⟶ 2,947:
<span style="color: #0000FF;">?{</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"/ 3 ="</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sq_div</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)}</span>
<span style="color: #0000FF;">?{</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"^ 3 ="</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sq_power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)}</span>
<!--</
{{out}}
<pre>
Line 2,980 ⟶ 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 3,014 ⟶ 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 3,022 ⟶ 3,005:
v = scalar * vector;
v = vector * vector;</
=={{header|Python}}==
<
>>> from operator import add, sub, mul, floordiv
>>> from pprint import pprint as pp
Line 3,067 ⟶ 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 3,073 ⟶ 3,056:
In R most operations work on vectors and matrices:
<
mat <- matrix(1:4, 2, 2)
Line 3,084 ⟶ 3,067:
mat + mat
mat * mat
mat ^ mat</
{{out}}
Line 3,124 ⟶ 3,107:
=={{header|Racket}}==
{{trans|R}}
<
(define mat (list->array #(2 2) '(1 3 2 4)))
Line 3,136 ⟶ 3,119:
(array* mat mat)
(array-map expt mat mat)
</syntaxhighlight>
{{out}}
Line 3,151 ⟶ 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 3,159 ⟶ 3,141:
sub msay(@x) {
say .map( { ($_%1) ?? $_.nude.join('/') !! $_ } ).join(' ') for @x;
say '';
}
Line 3,186 ⟶ 3,165:
msay @a M+ [1,2,3];
msay @a M+ 2;
</syntaxhighlight>
{{out}}
<pre> 2 4 6
Line 3,250 ⟶ 3,229:
=={{header|REXX}}==
===discrete===
<
m= (1 2 3) (4 5 6) (7 8 9)
w= words(m); do rows=1; if rows*rows>=w then leave
Line 3,282 ⟶ 3,261:
do c=1 for cols; n= n+1; _= _ right( word(@, n), L); end; say _
end
return</
{{out|output|text= when using the internal default input:}}
<pre style="height:73ex">
Line 3,327 ⟶ 3,306:
===generalized===
<
m= (1 2 3) (4 5 6) (7 8 9)
w= words(m); do rows=1; if rows*rows>=w then leave
Line 3,353 ⟶ 3,332:
do c=1 for cols; n= n+1; _= _ right( word(@, n), L); end; say _
end
return</
{{out|output|text= when using the internal default input:}}
<pre style="height:75ex">
Line 3,411 ⟶ 3,390:
=={{header|Ruby}}==
<
class Matrix
Line 3,426 ⟶ 3,405:
[:+, :-, :*, :/, :fdiv, :**, :%].each do |op|
puts "m1 %-4s m2 = %s" % [op, m1.element_wise(op, m2)]
end</
{{out}}
<pre>
Line 3,442 ⟶ 3,421:
=={{header|Rust}}==
<
elements: Vec<f32>,
pub height: u32,
Line 3,576 ⟶ 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 3,604 ⟶ 3,583:
say (m1 ~RS/ 42)
say (m1 ~RS** 10)
# ...</
{{out}}
<pre>
Line 3,630 ⟶ 3,609:
=={{header|Standard ML}}==
<
local
open Array2
Line 3,660 ⟶ 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,684 ⟶ 3,663:
a:/b
a:^b
end</
=={{header|Tcl}}==
<
proc alias {name args} {uplevel 1 [list interp alias {} $name {} {*}$args]}
Line 3,726 ⟶ 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,734 ⟶ 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,838 ⟶ 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,926 ⟶ 4,045:
=={{header|zkl}}==
<
M:=GSL.Matrix(3,3).set(3,5,7, 1,2,3, 2,4,6);
x:=2;
Line 3,937 ⟶ 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>
|