JuliaKurs23/nb/7_ArraysP2.ipynb

2055 lines
45 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "5c227958",
"metadata": {},
"source": [
"# Vektoren, Matrizen, Arrays\n",
"\n",
"## Allgemeines \n",
"\n",
"Kommen wir nun zu den wohl wichtigsten Containern für numerische Mathematik: \n",
"\n",
"- Vektoren `Vector{T}` \n",
"- Matrizen `Matrix{T}` mit zwei Indizes \n",
"- N-dimensionale Arrays mit N Indizes `Array{T,N}`\n",
"\n",
"Tatsächlich ist `Vector{T}` ein Alias für `Array{T,1}` und `Matrix{T}` ein Alias für `Array{T,2}`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ee55f3c2",
"metadata": {},
"outputs": [],
"source": [
"Vector{Float64} === Array{Float64,1} && Matrix{Float64} === Array{Float64,2}"
]
},
{
"cell_type": "markdown",
"id": "bc271209",
"metadata": {},
"source": [
"Beim Anlegen durch eine explizite Elementliste wird der 'kleinste gemeinsame Typ' für den Typparameter `T` ermittelt.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "93a9f521",
"metadata": {},
"outputs": [],
"source": [
"v = [33, \"33\", 1.2]"
]
},
{
"cell_type": "markdown",
"id": "3d2a9699",
"metadata": {},
"source": [
"Falls `T` ein numerischer Typ ist, werden die Elemente in diesen Typ umgewandelt.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6810b420",
"metadata": {},
"outputs": [],
"source": [
"v = [3//7, 4, 2im]"
]
},
{
"cell_type": "markdown",
"id": "cff4245f",
"metadata": {},
"source": [
"Informationen über einen Array liefern die Funktionen:\n",
"\n",
"- `length(A)` --- Anzahl der Elemente\n",
"- `eltype(A)` --- Typ der Elemente\n",
"- `ndims(A)` --- Anzahl der Dimensionen (Indizes)\n",
"- `size(A)` --- Tupel mit den Dimensionen des Arrays \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "79c5010b",
"metadata": {},
"outputs": [],
"source": [
"v1 = [12, 13, 15]\n",
"\n",
"m1 = [ 1 2.5\n",
" 6 -3 ]\n",
"\n",
"for f ∈ (length, eltype, ndims, size)\n",
" println(\"$(f)(v) = $(f(v)), $(f)(m1) = $(f(m1))\")\n",
"end"
]
},
{
"cell_type": "markdown",
"id": "dd306f62",
"metadata": {},
"source": [
"- Die Stärke des 'klassischen' Arrays für das wissenschaftliche Rechnen besteht darin, dass es einfach nur ein zusammenhängendes Speichersegment ist, in dem die Komponenten gleicher Länge (z.B. 64 Bit) geordnet hintereinander abgespeichert sind. Damit ist der Speicherbedarf minimal und die Zugriffsgeschwindigkeit auf eine Komponente, sowohl beim Lesen als auch beim Modifizieren, maximal. Der Platz der Komponente `v[i]` ist sofort aus `i` berechenbar. \n",
"- Julias `Array{T,N}` (und damit Vektoren und Matrizen) ist für die üblichen numerischen Typen `T` in dieser Weise implementiert. Die Elemente werden *unboxed* gespeichert. Im Gegensatz dazu ist z.B. ein `Vector{Any}` implementiert als Liste von Adressen von Objekten *(boxed)* und nicht als Liste der Objekte selbst. \n",
"- Julias `Array{T,N}` speichert seine Elemente direkt *(unboxed)*, wenn `isbitstype(T) == true`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3227cda0",
"metadata": {},
"outputs": [],
"source": [
"isbitstype(Float64), \n",
"isbitstype(Complex{Rational{Int64}}), \n",
"isbitstype(String)"
]
},
{
"cell_type": "markdown",
"id": "dd9c87cf",
"metadata": {},
"source": [
"## Vektoren\n",
"\n",
"### Listen-artige Funktionen \n",
"\n",
"- `push!(vector, items...)` --- fügt Elemente am Ende des Vektors an\n",
"- `pushfirst!(vector, items...)` --- fügt Elemente am Anfang des Vektors an\n",
"- `pop!(vector)` --- entfernt letztes Element und liefert es als Ergebnis zurück,\n",
"- `popfirst!(vector)` --- entfernt erstes Element und liefert es zurück \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f49c51ee",
"metadata": {},
"outputs": [],
"source": [
"v = Float64[] # leerer Vector{Float64}\n",
"\n",
"push!(v, 3, 7)\n",
"pushfirst!(v, 1)\n",
"\n",
"a = pop!(v)\n",
"println(\"a= $a\")\n",
"\n",
"push!(v, 17)"
]
},
{
"cell_type": "markdown",
"id": "d0bae695",
"metadata": {},
"source": [
"Ein `push!()` kann sehr aufwändig sein, da eventuell neuer Speicher alloziert und dann der ganze bestehende Vektor umkopiert werden muss. Julia optimiert das Speichermanagement. Es wird in einem solchen Fall Speicher auf Vorrat alloziert, so dass weitere `push!`s sehr schnell sind und man 'fast O(1)-Geschwindigkeit' erreicht. \n",
"\n",
"Trotzdem sollte man bei zeitkritischem Code und sehr großen Feldern Operationen wie `push!()` oder `resize()` vermeiden.\n",
"\n",
"### Weitere Konstruktoren\n",
"\n",
"Man kann Vektoren mit vorgegebener Länge und Typ uninitialisiert anlegen. Das geht am Schnellsten, die Elemente sind zufállige Bitmuster.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5dd7319a",
"metadata": {},
"outputs": [],
"source": [
"# fixe Länge 1000, uninitialisiert\n",
"\n",
"v = Vector{Float64}(undef, 1000)\n",
"v[345]"
]
},
{
"cell_type": "markdown",
"id": "d154d1d5",
"metadata": {},
"source": [
"- `zeros(n)` legt einen `Vector{Float64}` der Länge `n` an und initialisiert mit Null. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a4a098b6",
"metadata": {},
"outputs": [],
"source": [
"v = zeros(7) "
]
},
{
"cell_type": "markdown",
"id": "20e95a21",
"metadata": {},
"source": [
"- `zeros(T,n)` legt einen Nullvektor vom Typ `T` an.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3914deb9",
"metadata": {},
"outputs": [],
"source": [
"v=zeros(Int, 4)"
]
},
{
"cell_type": "markdown",
"id": "6ea61c0a",
"metadata": {},
"source": [
"- `fill(x, n)` legt `Vector{typeof(x)}` der Länfe `n` an und füllt mit `x`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "92180908",
"metadata": {},
"outputs": [],
"source": [
"v = fill(sqrt(2), 5)"
]
},
{
"cell_type": "markdown",
"id": "177266ed",
"metadata": {},
"source": [
"- `similar(v)` legt einen uninitialisierten Vektor von gleichem Typ und Größe wie `v` an.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b5479424",
"metadata": {},
"outputs": [],
"source": [
"w = similar(v)"
]
},
{
"cell_type": "markdown",
"id": "4ad4add1",
"metadata": {},
"source": [
"### Konstruktion durch implizite Schleife _(list comprehension)_\n",
"\n",
"Implizite `for`-Schleifen sind eine weitere Methode, Vektoren zu erzeugen.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2a281cdf",
"metadata": {},
"outputs": [],
"source": [
"v4 = [i for i in 1.0:8]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "afb33a9c",
"metadata": {},
"outputs": [],
"source": [
"v5 = [log(i^2) for i in 1:4 ]"
]
},
{
"cell_type": "markdown",
"id": "cde23de5",
"metadata": {},
"source": [
"Man kann sogar noch ein `if` unterbringen.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "88638841",
"metadata": {},
"outputs": [],
"source": [
"v6 = [i^2 for i in 1:8 if i%3 != 2]"
]
},
{
"cell_type": "markdown",
"id": "1ee31e25",
"metadata": {},
"source": [
"### Bitvektoren {#sec-bitvec}\n",
"\n",
"Neben `Vector{Bool}` gibt es noch den speziellen Datentyp `BitVector` (und allgemeiner auch `BitArray`) zur Speicherung von Feldern mit Wahrheitswerten. \n",
"\n",
"Während für die Speicherung eines `Bool`s ein Byte verwendet wird, erfolgt die Speicherung in einem BitVector bitweise. \n",
"\n",
"Der Konstruktor wandelt einen \n",
"`Vector{Bool}` in einen `BitVector` um.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "115aa38e",
"metadata": {},
"outputs": [],
"source": [
"vb = BitVector([true, false, true, true])"
]
},
{
"cell_type": "markdown",
"id": "dd064777",
"metadata": {},
"source": [
"Für die Gegenrichtung gibt es `collect()`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "035f3ce7",
"metadata": {},
"outputs": [],
"source": [
"collect(vb)"
]
},
{
"cell_type": "markdown",
"id": "b40e16c8",
"metadata": {},
"source": [
"BitVectoren entstehen z.B. als Ergebnis von elementweisen Vergleichen (s. @sec-broadcast).\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6b67988d",
"metadata": {},
"outputs": [],
"source": [
"v4 .> 3.5"
]
},
{
"cell_type": "markdown",
"id": "6095e15c",
"metadata": {},
"source": [
"### Indizierung\n",
"\n",
"Für den Mathematiker sind Indizes Ordinalzahlen. Also __startet die Indexzählung mit 1.__\n",
"\n",
"Als Index kann man verwenden:\n",
"\n",
" - Integer\n",
" - Integer-wertigen Range (gleiche Länge oder kürzer)\n",
" - Integer-Vektor (gleiche Länge oder kürzer)\n",
" - Bool-Vektor oder BitVector (gleiche Länge)\n",
" \n",
" \n",
"Mit Indizes kann man Arrayelemente/teile lesen und schreiben.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1e8f2011",
"metadata": {},
"outputs": [],
"source": [
"v = [ 3i + 5.2 for i in 1:8]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "61efc9b0",
"metadata": {},
"outputs": [],
"source": [
"v[5]"
]
},
{
"cell_type": "markdown",
"id": "005efaab",
"metadata": {},
"source": [
"Bei Zuweisungen wird die rechte Seite wenn nötig mit `convert(T,x)` in den Vektorelementetyp umgewandelt.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d29b8ddb",
"metadata": {},
"outputs": [],
"source": [
"v[6] = 9999\n",
"v"
]
},
{
"cell_type": "markdown",
"id": "4c1b08f5",
"metadata": {},
"source": [
"Überschreiten der Indexgrenzen führt zu einem `BoundsError`. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d8e26873",
"metadata": {},
"outputs": [],
"source": [
"v[77]"
]
},
{
"cell_type": "markdown",
"id": "43567db7",
"metadata": {},
"source": [
"Mit einem `range`-Objekt kann man einen Teilvektor adressieren.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "15f45e9d",
"metadata": {},
"outputs": [],
"source": [
"vp = v[3:5]\n",
"vp"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c52da06e",
"metadata": {},
"outputs": [],
"source": [
"vp = v[1:2:7] # range mit Schrittweite\n",
"vp"
]
},
{
"cell_type": "markdown",
"id": "d6e45504",
"metadata": {},
"source": [
"- Bei der Verwendung als Index kann in einem Range der Spezialwert `end` verwendet werden.\n",
"- Bei der Verwendung als Index kann der \"leere\" Range `:` als Abkürzung von `1:end` verwendet werden. Das ist nützlich bei Matrizen: `A[:, 3]` addresiert die gesamte 3. Spalte von `A`. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6f73e624",
"metadata": {},
"outputs": [],
"source": [
"v[6:end] = [7, 7, 7]\n",
"v"
]
},
{
"cell_type": "markdown",
"id": "ff325674",
"metadata": {},
"source": [
"#### Indirekte Indizierung\n",
"\n",
"Die indirekte Indizierung mit einem *Vector of Integers/Indices* erfolgt nach der Formel \n",
"\n",
"\n",
"$v[ [i_1,\\ i_2,\\ i_3,...]] = [\\ v[i_1],\\ v[i_2],\\ v[i_3],...]$\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bf53ca2b",
"metadata": {},
"outputs": [],
"source": [
"v[ [1, 3, 4] ]"
]
},
{
"cell_type": "markdown",
"id": "7b2f2bc8",
"metadata": {},
"source": [
"ist also gleich\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4f5fec9d",
"metadata": {},
"outputs": [],
"source": [
"[ v[1], v[3], v[4] ]"
]
},
{
"cell_type": "markdown",
"id": "d24e3956",
"metadata": {},
"source": [
"#### Indizierung mit einem Vektor von Wahrheitswerten\n",
"\n",
"Als Index kann man auch einen `Vector{Bool}` oder `BitVector` (s. @sec-bitvec) **derselben Länge** verwenden. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9af04e7e",
"metadata": {},
"outputs": [],
"source": [
"v[ [true, true, false, false, true, false, true, true] ]"
]
},
{
"cell_type": "markdown",
"id": "7d64ac85",
"metadata": {},
"source": [
"Das ist nützlich, da man z.B.\n",
"\n",
" - Tests broadcasten kann (s. @sec-broadcast),\n",
" - diese Tests dann einen BitVector liefern und\n",
" - bei Bedarf solche Bitvektoren durch die Bit-weisen Operatoren `&` und `|` verknüpft werden können. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "670b80ea",
"metadata": {},
"outputs": [],
"source": [
"v[ (v .> 13) .& (v.<20) ]"
]
},
{
"cell_type": "markdown",
"id": "7bc7e5fb",
"metadata": {},
"source": [
"## Matrizen und Arrays\n",
"\n",
"Die bisher vorgestellten Methoden für Vektoren übertragen sich auch auf höherdimensionale Arrays.\n",
"\n",
"Man kann sie uninitialisiert anlegen:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f4c8b14c",
"metadata": {},
"outputs": [],
"source": [
"A = Array{Float64,3}(undef, 6,9,3)"
]
},
{
"cell_type": "markdown",
"id": "b692ddb4",
"metadata": {},
"source": [
"In den meisten Funktionen kann man die Dimensionen auch als Tupel übergeben. Die obige Anweisung lässt sich auch so schreiben:\n",
"\n",
"```julia\n",
"A = Array{Float64, 3}(undef, (6,9,3)) \n",
"```\n",
"\n",
"Funktionen wie `zeros()` usw. funktionieren natürlich auch.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c7b17431",
"metadata": {},
"outputs": [],
"source": [
"m2 = zeros(3, 4, 2) # oder zeros((3,4,2)) "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f361ecf8",
"metadata": {},
"outputs": [],
"source": [
"M = fill(5 , (3, 3)) # oder fill(5, 3, 3)"
]
},
{
"cell_type": "markdown",
"id": "68ac511a",
"metadata": {},
"source": [
"Die Funktion `similar()`, die einen Array gleicher Größe uninitialisiert erzeugt, kann auch einen Typ als weiteres Argument bekommen.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3a0958e2",
"metadata": {},
"outputs": [],
"source": [
"M2 = similar(M, Float64)"
]
},
{
"cell_type": "markdown",
"id": "027fb6d6",
"metadata": {},
"source": [
"### Konstruktion durch explizite Elementliste\n",
"\n",
"Während man Vektoren kommagetrennt in eckigen Klammern notiert, ist die Notation für höherdimensionale Objekte etwas anders. \n",
"\n",
"- Eine Matrix:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ba838fe7",
"metadata": {},
"outputs": [],
"source": [
"M2 = [2 3 -1\n",
" 4 5 -2]"
]
},
{
"cell_type": "markdown",
"id": "5254a785",
"metadata": {},
"source": [
"- dieselbe Matrix:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4878b4e0",
"metadata": {},
"outputs": [],
"source": [
"M2 = [2 3 -1; 4 5 -2]"
]
},
{
"cell_type": "markdown",
"id": "48b415e9",
"metadata": {},
"source": [
"- Ein Array mit 3 Indizes:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c0e45334",
"metadata": {},
"outputs": [],
"source": [
"M3 = [2 3 -1 \n",
" 4 5 6 ;;;\n",
" 7 8 9\n",
" 11 12 13]"
]
},
{
"cell_type": "markdown",
"id": "aedabca8",
"metadata": {},
"source": [
"- und nochmal die Matrix `M2`:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3537604f",
"metadata": {},
"outputs": [],
"source": [
"M2 = [2;4;; 3;5;; -1;-2]"
]
},
{
"cell_type": "markdown",
"id": "8b21f42d",
"metadata": {},
"source": [
"Im letzten Beispiel kommen diese Regeln zur Anwendung:\n",
"\n",
"- Trenner ist das Semikolon.\n",
"- Ein Semikolon `;` erhöht den 1. Index.\n",
"- Zwei Semikolons `;;` erhöhen den 2. Index.\n",
"- Drei Semikolons `;;;` erhöhen den 3. Index usw. \n",
"\n",
"In den Beispielen davor wurde folgende Syntaktische Verschönerung (_syntactic sugar_) angewendet:\n",
"\n",
"- Leerzeichen trennen wie 2 Semikolons -- erhöht also den 2. Index: $\\quad a_{12}\\quad a_{13}\\quad a_{14}\\ ...$\n",
"- Zeilenumbruch trennt wie ein Semikolon -- erhöht also den 1. Index.\n",
"\n",
"\n",
":::{.callout-important}\n",
"\n",
"- Vektorschreibweise mit Komma als Trenner geht nur bei Vektoren, nicht mit \"Semikolon, Leerzeichen, Newline' mischen! \n",
"- Vektoren mit einem Index; $1\\!\\times\\!n$-Matrizen und $n\\!\\times\\!1$-Matrizen sind drei verschiedene Dinge!\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5068d43b",
"metadata": {},
"outputs": [],
"source": [
"v1 = [2,3,4]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "251a03fc",
"metadata": {},
"outputs": [],
"source": [
"v2 = [2;3;4]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "12be7f1d",
"metadata": {},
"outputs": [],
"source": [
"v3 = [2 3 4]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "41a648f3",
"metadata": {},
"outputs": [],
"source": [
"v3 = [2;3;4;;]"
]
},
{
"cell_type": "markdown",
"id": "e16508b2",
"metadata": {},
"source": [
":::\n",
"\n",
"\n",
"Einen \"vector of vectors\" a la C/C++ kann man natürlich auch konstruieren. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8d20c99f",
"metadata": {},
"outputs": [],
"source": [
"v = [[2,3,4], [5,6,7,8]]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7acc9cd7",
"metadata": {},
"outputs": [],
"source": [
"v[2][3]"
]
},
{
"cell_type": "markdown",
"id": "36081804",
"metadata": {},
"source": [
"Das sollte man nur in Spezialfällen tun. Die Array-Sprache von Julia ist in der Regel bequemer und schneller.\n",
"\n",
"### Indizes, Teilfelder, Slices\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8dbddd28",
"metadata": {},
"outputs": [],
"source": [
"# 6x6 Matrix mit Zufallszahlen gleichverteilt aus [0,1) ∈ Float64\n",
"A = rand(6,6)"
]
},
{
"cell_type": "markdown",
"id": "86dcdd80",
"metadata": {},
"source": [
"Die übliche Indexnotation:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6457e824",
"metadata": {},
"outputs": [],
"source": [
"A[2, 3] = 77.77777\n",
"A"
]
},
{
"cell_type": "markdown",
"id": "ed38064b",
"metadata": {},
"source": [
"Man kann mit Ranges Teilfelder adressieren:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "865b7b29",
"metadata": {},
"outputs": [],
"source": [
"B = A[1:2, 1:3]"
]
},
{
"cell_type": "markdown",
"id": "eafd8cc8",
"metadata": {},
"source": [
"Das Adressieren von Teilen mit geringerer Dimension wird auch *slicing* genannt.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "aba3e4ef",
"metadata": {},
"outputs": [],
"source": [
"# die 3. Spalte als Vektor (slicing)\n",
"\n",
"C = A[:, 3]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "14259946",
"metadata": {},
"outputs": [],
"source": [
"# die 3. Zeile als Vektor (slicing)\n",
"\n",
"E = A[3, :]"
]
},
{
"cell_type": "markdown",
"id": "bec96c71",
"metadata": {},
"source": [
"Natürlich sind damit auch Zuweisungen möglich:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "82f68a6e",
"metadata": {},
"outputs": [],
"source": [
"# Man kann slices und Teilfeldern auch etwas zuweisen \n",
"\n",
"A[2, :] = [1,2,3,4,5,6]\n",
"A"
]
},
{
"cell_type": "markdown",
"id": "23dd1440",
"metadata": {},
"source": [
"## Verhalten bei Zuweisungen, `copy()` und `deepcopy()`, Views\n",
"\n",
"### Zuweisungen und Kopien\n",
"\n",
"- Variablen sind Referenzen auf Objekte. \n",
"- _Eine Zuweisung zu einer Variablen erzeugt kein neues Objekt._\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2499e260",
"metadata": {},
"outputs": [],
"source": [
"A = [1, 2, 3]\n",
"B = A"
]
},
{
"cell_type": "markdown",
"id": "4c9e3a04",
"metadata": {},
"source": [
"`A` und `B` sind jetzt Namen desselben Objekts.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9fdad306",
"metadata": {},
"outputs": [],
"source": [
"A[1] = 77\n",
"@show B;"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c51812e7",
"metadata": {},
"outputs": [],
"source": [
"B[3] = 300\n",
"@show A;"
]
},
{
"cell_type": "markdown",
"id": "00fe556c",
"metadata": {},
"source": [
"Dieses Verhalten spart viel Zeit und Speicher, ist aber nicht immer gewünscht. \n",
"Die Funktion `copy()` erzeugt eine 'echte' Kopie des Objekts.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b71aff22",
"metadata": {},
"outputs": [],
"source": [
"A = [1, 2, 3]\n",
"B = copy(A)\n",
"A[1] = 100\n",
"@show A B;"
]
},
{
"cell_type": "markdown",
"id": "03f55f43",
"metadata": {},
"source": [
"Die Funktion \n",
"`deepcopy(A)` kopiert rekursiv. Auch von den Elementen, aus denen `A` besteht, werden (wieder rekursive) Kopien erstellt. \n",
"\n",
"Solange ein Array nur primitive Objekte (Zahlen) enthält, sind `copy()` und `deepcopy()` äquivalent. \n",
"\n",
"Das folgende Beispiel zeigt den Unterschied zwischen `copy()` und `deepcopy()`.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "75c537cc",
"metadata": {},
"outputs": [],
"source": [
"mutable struct Person\n",
" name :: String\n",
" age :: Int\n",
"end\n",
"\n",
"A = [Person(\"Meier\", 20), Person(\"Müller\", 21), Person(\"Schmidt\", 23)]\n",
"B = A\n",
"C = copy(A)\n",
"D = deepcopy(A)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5721ca90",
"metadata": {},
"outputs": [],
"source": [
"A[1] = Person(\"Mustermann\", 83)\n",
"A[3].age = 199 \n",
"\n",
"@show B C D;"
]
},
{
"cell_type": "markdown",
"id": "f9ebeba5",
"metadata": {},
"source": [
"### Views\n",
"\n",
"Wenn man mittels *indices/ranges/slices* einer Variablen ein Teilstück eines Arrays zuweist, \n",
"wird von Julia grundsätzlich **ein neues Objekt** konstruiert.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d17cb1dd",
"metadata": {},
"outputs": [],
"source": [
"A = [1 2 3\n",
" 3 4 5]\n",
"\n",
"v = A[:, 2]\n",
"@show v\n",
"\n",
"A[1, 2] = 77\n",
"@show A v;"
]
},
{
"cell_type": "markdown",
"id": "3b5120b7",
"metadata": {},
"source": [
"Manchmal möchte man aber gerade hier eine Referenz-Semantik haben im Sinne von: \"Vektor `v` soll der 2. Spaltenvektor von `A` sein und auch bleiben (d.h., sich mitändern, wenn sich `A` ändert).\"\n",
"\n",
"Dies bezeichnet man in Julia als *views*: Wir wollen, dass die Variable `v` nur einen 'alternativen Blick' auf die Matrix `A` darstellt.\n",
"\n",
"Das kann man erreichen durch das `@view`-Macro: \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c86c7a1f",
"metadata": {},
"outputs": [],
"source": [
"A = [1 2 3\n",
" 3 4 5]\n",
"\n",
"v = @view A[:,2]\n",
"@show v\n",
"\n",
"A[1, 2] = 77\n",
"@show v;"
]
},
{
"cell_type": "markdown",
"id": "d076c1a5",
"metadata": {},
"source": [
"Diese Technik wird von Julia aus Effizienzgründen auch bei einigen Funktionen der linearen Algebra verwendet. \n",
"Ein Beispiel ist der Operator `'`, der zu einer Matrix `A` die adjungierte Matrix `A'` liefert.\n",
"\n",
"- Die adjungierte _(adjoint)_ Matrix `A'` ist die transponierte und elementweise komplex-konjugierte Matrix zu `A`. \n",
"- Der Parser macht daraus den Funktionsaufruf `adjoint(A)`. \n",
"- Für reelle Matrizen ist die Adjungierte gleich der transponierten Matrix.\n",
"- Julia implementiert `adjoint()` als _lazy function_, d.h., \n",
"- es wird aus Effizienzgründen kein neues Objekt konstruiert, sondern nur ein alternativer 'View' auf die Matrix (\"mit vertauschten Indizes\") und ein alternativer 'View' auf die Einträge (mit Vorzeichenwechsel im Imaginärteil).\n",
"- Aus Vektoren macht `adjoint()` eine $1\\!\\times\\!n$-Matrix (einen Zeilenvektor).\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f3bae50e",
"metadata": {},
"outputs": [],
"source": [
"A = [ 1. 2.\n",
" 3. 4.]\n",
"B = A'"
]
},
{
"cell_type": "markdown",
"id": "67138cff",
"metadata": {},
"source": [
"Die Matrix `B` ist nur ein modifizierter 'View' auf `A`:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "829acf4c",
"metadata": {},
"outputs": [],
"source": [
"A[1, 2] =10\n",
"B"
]
},
{
"cell_type": "markdown",
"id": "e3c2a66c",
"metadata": {},
"source": [
"Aus Vektoren macht `adjoint()` eine $1\\!\\times\\!n$-Matrix (einen Zeilenvektor).\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "78065100",
"metadata": {},
"outputs": [],
"source": [
"v = [1, 2, 3]\n",
"v'"
]
},
{
"cell_type": "markdown",
"id": "a5d85afa",
"metadata": {},
"source": [
"Eine weitere solche Funktion, die einen alternativen 'View', eine andere Indizierung, derselben Daten \n",
"liefert, ist `reshape()`. \n",
"\n",
"Hier wird ein Vektor mit 12 Einträgen in eine 3x4-Matrix verwandelt.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7c31328d",
"metadata": {},
"outputs": [],
"source": [
"A = [1,2,3,4,5,6,7,8,9,10,11,12]\n",
"\n",
"B = reshape(A, 3, 4) "
]
},
{
"cell_type": "markdown",
"id": "ab0bb6f9",
"metadata": {},
"source": [
"## Speicherung eines Arrays\n",
"\n",
"- Speicher wird linear adressiert. Eine Matrix kann zeilenweise _(row major)_ oder spaltenweise _(column major)_ im Speicher angeordnet sein. \n",
"- C/C++/Python(NumPy) verwenden eine zeilenweise Speicherung: Die 4 Elemente einer 2x2-Matrix sind abgespeichert in der Reihenfolge $a_{11},a_{12},a_{21},a_{22}$. \n",
"- Julia, Fortran, Matlab speichern spaltenweise: $a_{11},a_{21},a_{12},a_{22}$. \n",
"\n",
"Diese Information ist wichtig, um effizient über Matrizen zu iterieren:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e6b341f8",
"metadata": {},
"outputs": [],
"source": [
"function column_major_add(A, B)\n",
" (n,m) = size(A)\n",
" for j = 1:m\n",
" for i = 1:n # innere Schleife durchläuft eine Spalte\n",
" A[i,j] += B[i,j]\n",
" end\n",
" end\n",
"end\n",
"\n",
"function row_major_add(A, B)\n",
" (n,m) = size(A)\n",
" for i = 1:n\n",
" for j = 1:m # inere Schleife durchläuft eine Zeile\n",
" A[i,j] += B[i,j]\n",
" end\n",
" end\n",
"end"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "02e841a6",
"metadata": {},
"outputs": [],
"source": [
"A = rand(10000, 10000);\n",
"B = rand(10000, 10000);"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "977e691b",
"metadata": {},
"outputs": [],
"source": [
"using BenchmarkTools\n",
"\n",
"@benchmark row_major_add($A, $B) "
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1e5df44b",
"metadata": {},
"outputs": [],
"source": [
"@benchmark column_major_add($A, $B)"
]
},
{
"cell_type": "markdown",
"id": "c75b3f1d",
"metadata": {},
"source": [
"### Lokalität von Speicherzugriffen und _Caching_\n",
"\n",
"Wir haben gesehen, dass die Reihenfolge von innerem und äußerem Loop einen erheblichen Geschwindigkeitsunterschied macht:\n",
"\n",
"__Es ist effizienter, wenn die innerste Schleife über den linken Index läuft__, also eine Spalte und nicht eine Zeile durchläuft. Die Ursache dafür liegt in der Architektur moderner Prozessoren.\n",
"\n",
"- Speicherzugriffe erfolgt über mehrere Cache-Ebenen. \n",
"- Ein _cache miss_, der ein Nachladen aus langsameren Caches auslöst, bremst aus.\n",
"- Es werden immer gleich größere Speicherblöcke nachgeladen, um die Häufigkeit von _cache misses_ zu minimieren.\n",
"- Daher ist es wichtig, Speicherzugriffe möglichst lokal zu organisieren.\n",
"\n",
"::: {.content-visible when-format=\"html\"}\n",
"![Speicherhierarchie von Intel-Prozessoren, aus: Victor Eijkhout,_Introduction to High-Performance Scientific Computing_, [https://theartofhpc.com/](https://theartofhpc.com/)](../images/cache.png){width=\"75%\"}\n",
"\n",
":::\n",
"\n",
"::: {.content-visible when-format=\"pdf\"}\n",
"![Speicherhierarchie von Intel-Prozessoren, aus: Victor Eijkhout,_Introduction to High-Performance Scientific Computing_, [https://theartofhpc.com/](https://theartofhpc.com/)](../images/cache.png){width=\"70%\"}\n",
":::\n",
"\n",
"\n",
"## Mathematische Operationen mit Arrays\n",
"\n",
"Arrays der gleichen Dimension (z.B. alle $7\\!\\times\\!3$-Matrizen) bilden einen linearen Raum. \n",
"\n",
" - Sie können mit Skalaren multipliziert werden und\n",
" - sie können addiert und subtrahiert werden.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "af7e8988",
"metadata": {},
"outputs": [],
"source": [
"0.5 * [2, 3, 4, 5]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b37890ac",
"metadata": {},
"outputs": [],
"source": [
"0.5 * [ 1 3\n",
" 2 7] - [ 2 3; 1 2]"
]
},
{
"cell_type": "markdown",
"id": "62d17bc4",
"metadata": {},
"source": [
"### Matrixprodukt\n",
"\n",
"Das Matrixprodukt ist definiert für \n",
"\n",
":::{.narrow}\n",
"\n",
"| 1. Faktor | 2. Faktor | Produkt |\n",
"| :-: | :-: | :-: |\n",
"| $(n\\!\\times\\!m)$-Matrix | $(m\\!\\times\\!k)$-Matrix | $(n\\times k)$-Matrix|\n",
"| $(n\\!\\times\\!m)$-Matrix | $m$-Vektor | $n$-Vektor |\n",
"| $(1\\!\\times\\!m)$-Zeilenvektor | $(m\\!\\times\\!n)$-Matrix | $n$-Vektor |\n",
"| $(1\\!\\times\\!m)$-Zeilenvektor | $m$-Vektor | Skalarprodukt |\n",
"| $m$-Vektor | $(1\\times n)$-Zeilenvektor | $(m\\!\\times\\!n)$-Matrix |\n",
"\n",
":::\n",
"\n",
"Beispiele:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bfd0201f",
"metadata": {},
"outputs": [],
"source": [
"A = [1 2 3\n",
" 4 5 6]\n",
"v = [2, 3]\n",
"w = [1, 3, 4];"
]
},
{
"cell_type": "markdown",
"id": "78eb3a67",
"metadata": {},
"source": [
"- (2,3)-Matrix `*` (3,2)-Matrix\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5012734f",
"metadata": {},
"outputs": [],
"source": [
"A * A'"
]
},
{
"cell_type": "markdown",
"id": "6853f87e",
"metadata": {},
"source": [
"- (3,2)-Matrix `*` (2,3)-Matrix\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0043d2e3",
"metadata": {},
"outputs": [],
"source": [
"A' * A"
]
},
{
"cell_type": "markdown",
"id": "2f8fef4c",
"metadata": {},
"source": [
"- (2,3)-Matrix `*` 3-Vektor\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b12cbb35",
"metadata": {},
"outputs": [],
"source": [
"A * w"
]
},
{
"cell_type": "markdown",
"id": "80ba832f",
"metadata": {},
"source": [
"- (1,2)-Vektore `*` (2,3)-Matrix\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f832930e",
"metadata": {},
"outputs": [],
"source": [
"v' * A"
]
},
{
"cell_type": "markdown",
"id": "30ccb92a",
"metadata": {},
"source": [
"- (3,2)-Matrix `*` 2-Vektor\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "20668407",
"metadata": {},
"outputs": [],
"source": [
"A' * v"
]
},
{
"cell_type": "markdown",
"id": "11148039",
"metadata": {},
"source": [
"- (1,2)-Vektor `*` 2-Vektor (Skalarprodukt)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b7f89eac",
"metadata": {},
"outputs": [],
"source": [
"v' * v"
]
},
{
"cell_type": "markdown",
"id": "a6c08a07",
"metadata": {},
"source": [
"2-Vektor `*` (1,3)-Vektor (äußeres Produkt) \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "71f47541",
"metadata": {},
"outputs": [],
"source": [
"v * w'"
]
},
{
"cell_type": "markdown",
"id": "7d1fe459",
"metadata": {},
"source": [
"## Broadcasting {#sec-broadcast}\n",
"\n",
"- Beim _broadcasting_ werden Operationen oder Funktionen __elementweise__ auf Arrays angewendet.\n",
"- Die Syntax dafür ist ein Punkt _vor_ einem Operationszeichen oder _nach_ einem Funktionsnamen. \n",
"- Der Parser setzt `f.(x,y)` um zu `broadcast(f, x, y)` und analog für Operatoren `x .⊙ y` zu `broadcast(⊙, z, y)`. \n",
"- Dabei werden Operanden, denen eine oder mehrere Dimensionen fehlen, in diesen Dimensionen (virtuell) vervielfältigt. \n",
"- Das *broadcasting* von Zuweisungen `.=`, `.+=`,... verändert die Semantik. Es wird kein neues Objekt erzeugt, sondern die Werte werden in das links stehende Objekt (welches die richtige Dimension haben muss) eingetragen.\n",
"\n",
"\n",
"Einige Beispiele:\n",
"\n",
"- Elementweise Anwendung einer Funktion\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3b2f54bd",
"metadata": {},
"outputs": [],
"source": [
"sin.([1, 2, 3])"
]
},
{
"cell_type": "markdown",
"id": "9e2b6b10",
"metadata": {},
"source": [
"- Das Folgende liefert nicht die algebraische [Wurzel aus einer Matrix](https://de.wikipedia.org/wiki/Quadratwurzel_einer_Matrix), sondern die elementweise Wurzel aus jedem Eintrag. \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "eed676ee",
"metadata": {},
"outputs": [],
"source": [
"A = [8 2\n",
" 3 4]\n",
"\n",
"sqrt.(A)"
]
},
{
"cell_type": "markdown",
"id": "ae8a2b5e",
"metadata": {},
"source": [
"- Das Folgende liefert nicht $A^2$, sondern die Einträge werden quadriert.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0cc93370",
"metadata": {},
"outputs": [],
"source": [
"A.^2 "
]
},
{
"cell_type": "markdown",
"id": "3f8e55c6",
"metadata": {},
"source": [
"- Zum Vergleich das Ergenmis der algebraischen Operationen:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f1b97fa1",
"metadata": {},
"outputs": [],
"source": [
"@show A^2 A^(1/2);"
]
},
{
"cell_type": "markdown",
"id": "6e3c2f80",
"metadata": {},
"source": [
"- Broadcasting geht auch mit Funktionen mehrerer Variablen.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "14763047",
"metadata": {},
"outputs": [],
"source": [
"hyp(a,b) = sqrt(a^2+b^2)\n",
"\n",
"B = [3 4\n",
" 5 7]\n",
"\n",
"hyp.(A, B) "
]
},
{
"cell_type": "markdown",
"id": "7c23f048",
"metadata": {},
"source": [
"Bei Operanden verschiedener Dimension wird der Operand mit fehlenden Dimensionen in diesen durch Vervielfältigung virtuell \n",
"'aufgeblasen'.\n",
"\n",
"Wir addieren einen Skalar zu einer Matrix:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d1186a3d",
"metadata": {},
"outputs": [],
"source": [
"A = [ 1 2 3\n",
" 4 5 6]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ca261d61",
"metadata": {},
"outputs": [],
"source": [
"A .+ 300"
]
},
{
"cell_type": "markdown",
"id": "88d70780",
"metadata": {},
"source": [
"Der Skalar wurde durch Replikation auf dieselbe Dimension wie die Matrix gebracht. Wir lassen uns von `broadcast()` die Form des 2. Operanden nach dem *broadcasting* anzeigen: \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c48e84e2",
"metadata": {},
"outputs": [],
"source": [
"broadcast( (x,y) -> y, A, 300)"
]
},
{
"cell_type": "markdown",
"id": "021a47a6",
"metadata": {},
"source": [
"(Natürlich findet diese Replikation nur virtuell statt. Dieses Objekt wird bei anderen Operationen nicht wirklich erzeugt.)\n",
"\n",
"Als weiteres Beispiel: Matrix und (Spalten-)Vektor\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "769ea0eb",
"metadata": {},
"outputs": [],
"source": [
"A .+ [10, 20]"
]
},
{
"cell_type": "markdown",
"id": "458cdda2",
"metadata": {},
"source": [
"Der Vektor wird durch Wiederholung der Spalten aufgeblasen:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fa093187",
"metadata": {},
"outputs": [],
"source": [
"broadcast((x,y)->y, A, [10,20])"
]
},
{
"cell_type": "markdown",
"id": "a5fa929f",
"metadata": {},
"source": [
"Matrix und Zeilenvektor: Der Zeilenvektor wird zeilenweise vervielfältigt:\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c3d35884",
"metadata": {},
"outputs": [],
"source": [
"A .* [1,2,3]' # Adjungierter Vektor"
]
},
{
"cell_type": "markdown",
"id": "01cd8879",
"metadata": {},
"source": [
"Der 2. Operand wird von `broadcast()` durch Vervielfältigung der Zeilen 'aufgeblasen'.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2e90d0b0",
"metadata": {},
"outputs": [],
"source": [
"broadcast((x,y)->y, A, [1,2,3]')"
]
},
{
"cell_type": "markdown",
"id": "6d5febb2",
"metadata": {},
"source": [
"#### _Broadcasting_ bei Zuweisungen\n",
"\n",
"Zuweisungen `=`, `+=`, `/=`,..., bei denen links ein Name steht, laufen in Julia so ab, dass aus der rechten Seite ein Objekt konstruiert und diesem Objekt der neue Name zugewiesen wird. \n",
"\n",
"Beim Arbeiten mit Arrays will man allerdings sehr oft aus Effizienzgründen einen bestehenden Array weiterverwenden. Die rechts berechneten Einträge sollen in das bereits existierende Objekt auf der linken Seite eingetragen werden. \n",
"\n",
"Das erreicht man mit den Broadcast-Varianten `.=`, `.+=`,... der Zuweisungsoperatoren.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "14dece22",
"metadata": {},
"outputs": [],
"source": [
"A .= 3"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3b73a744",
"metadata": {},
"outputs": [],
"source": [
"A .+= [1, 4]"
]
},
{
"cell_type": "markdown",
"id": "33ad4d5e",
"metadata": {},
"source": [
"## Weitere Array-Funktionen - eine Auswahl\n",
"\n",
"Julia stellt eine große Anzahl von Funktionen bereit, die mit Arrays arbeiten.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "04f8dc09",
"metadata": {},
"outputs": [],
"source": [
"A = [22 -17 8 ; 4 6 9]"
]
},
{
"cell_type": "markdown",
"id": "58ce80a0",
"metadata": {},
"source": [
"- Finde das Maximum\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "34487039",
"metadata": {},
"outputs": [],
"source": [
"maximum(A)"
]
},
{
"cell_type": "markdown",
"id": "d17e1a0d",
"metadata": {},
"source": [
"- Finde das Maximum jeder Spalte\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "801f2031",
"metadata": {},
"outputs": [],
"source": [
"maximum(A, dims=1) "
]
},
{
"cell_type": "markdown",
"id": "2478bd06",
"metadata": {},
"source": [
"- Finde das Maximum jeder Zeile\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "85671a6a",
"metadata": {},
"outputs": [],
"source": [
"maximum(A, dims=2)"
]
},
{
"cell_type": "markdown",
"id": "acb7426d",
"metadata": {},
"source": [
"- Finde das Minimum und seine Position\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e6dd832a",
"metadata": {},
"outputs": [],
"source": [
"amin, i = findmin(A)"
]
},
{
"cell_type": "markdown",
"id": "42cca03b",
"metadata": {},
"source": [
"- Was ist ein `CatesianIndex`?\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f07d0f44",
"metadata": {},
"outputs": [],
"source": [
"dump(i)"
]
},
{
"cell_type": "markdown",
"id": "ad46031d",
"metadata": {},
"source": [
"- Extrahiere die Indizes des Minimum als Tupel\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "73fee196",
"metadata": {},
"outputs": [],
"source": [
"i.I"
]
},
{
"cell_type": "markdown",
"id": "eb657bc1",
"metadata": {},
"source": [
"- Summe und Produkt aller Einträge\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "56363941",
"metadata": {},
"outputs": [],
"source": [
"sum(A), prod(A)"
]
},
{
"cell_type": "markdown",
"id": "c7cf919e",
"metadata": {},
"source": [
"- Spaltensumme (1. Index wird reduziert)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c6fecc3b",
"metadata": {},
"outputs": [],
"source": [
"sum(A, dims=1) "
]
},
{
"cell_type": "markdown",
"id": "5081b4da",
"metadata": {},
"source": [
"- Zeilensummen (2. Index wird reduziert)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a1099f5a",
"metadata": {},
"outputs": [],
"source": [
"sum(A, dims=2) "
]
},
{
"cell_type": "markdown",
"id": "05404237",
"metadata": {},
"source": [
"- Summiere nach elementweiser Anwendung einer Funktion\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fcd3a0a8",
"metadata": {},
"outputs": [],
"source": [
"sum(x->sqrt(abs(x)), A) # sum_ij sqrt(|a_ij|)"
]
},
{
"cell_type": "markdown",
"id": "59f9b755",
"metadata": {},
"source": [
"- Reduziere (falte) den Array mit einer Funktion\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a7ecdced",
"metadata": {},
"outputs": [],
"source": [
"reduce(+, A) # equivalent to sum(A)"
]
},
{
"cell_type": "markdown",
"id": "c72dff31",
"metadata": {},
"source": [
"- `mapreduce(f, op, array)`: Wende `f` auf alle Einträge an, dann reduziere mit `op`\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "99dc2a14",
"metadata": {},
"outputs": [],
"source": [
"mapreduce(x -> x^2, +, A ) # Summe der Quadrate aller Einträge"
]
},
{
"cell_type": "markdown",
"id": "de530920",
"metadata": {},
"source": [
"- Gibt es Elemente in A, die > 5 sind? \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "53d33e6c",
"metadata": {},
"outputs": [],
"source": [
"any(x -> x>5, A) "
]
},
{
"cell_type": "markdown",
"id": "9dea54d7",
"metadata": {},
"source": [
"- Wieviele Elemente in A sind > 5?\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7dbdc21b",
"metadata": {},
"outputs": [],
"source": [
"count(x-> x>5, A) "
]
},
{
"cell_type": "markdown",
"id": "6c57c62e",
"metadata": {},
"source": [
"- sind alle Einträge positiv?\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "394308c2",
"metadata": {},
"outputs": [],
"source": [
"all(x-> x>0, A)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Julia 1.8.5",
"language": "julia",
"name": "julia-1.8"
}
},
"nbformat": 4,
"nbformat_minor": 5
}