Upload
others
View
7
Download
0
Embed Size (px)
Citation preview
1
computational geodynamics Goethe University of Frankfurt
Einführung in wissenschaftliche Programmiersprachen mit Geo-Anwendungen (GeoNumerik)
Do 9 ct – 11:45 in Geowiss-GW 2.106 = Linux-Pool IH. Wallner [email protected]
3. Tag Plan
MatLab – Einführung - parallel anwendenUmgebung, Hilfe, Taschenrechner, Variablennamen,
Datentypen, Matrizzen, Magisches Quadrat von Dürer
Operatoren, Ausgabe, Speichern/Laden, IO,
Kontrollstrukturen, Functions, Intrinsische,
2D Grafik, Figure, 3D Grafik Aufgaben
computational geodynamics Goethe University of Frankfurt
Ffm, 02. Mai 2013
2
computational geodynamics Goethe University of Frankfurt
MatLab Matrix Laboratory
ist interaktiv, matrixorientiert, objektorientiert, und programmierbarfür Berechnungen und Visualisierungvon wissenschaftlich-technischen Aufgaben
Umgebung Starten mit matlab & (eventuell mit Optionen) Desktop mit Menü und Leisten, Command Window und weiteren (Workspace, Directories, History,...)
Hilfe help so oder mit <function> lookfor <searchitem> oder HTML-Dokus oder pdfs (wie using_ml.pdf ) oder web-googeling (64 Millonen Links)
3
computational geodynamics Goethe University of Frankfurt
MatLab Matrix Laboratory
ist ein mächtiger Taschenrechner13+8ans = 21 und mehr
Variablennamen <63 Zeichen (A-Z,a-z,0-9,_), 1.: Buchstabe Zahlen: 2, 3.4, -5.3E3, -.065Datentypen fast alles sind Matrizen mit double – Komponenten a=13, who, whos a(2,3)=23, b=[11 12; 21 22]; b Komplexe Zahlen c=7+8i, real(c), imag(c) Zeichenketten/Strings s1='Text', s2=['2ter ' s1] Strukturen D.title='I am D-structure', D.number=13, D.vector=[ 1 2 3] hierarchisch Cell-Arrays ca={'a cell-element' 21.17 eye(3) D}, ca{3} Container mit verschiedenen Datentypen 4
computational geodynamics Goethe University of Frankfurt
MatLab
Matrizzen Definition mit [ ], Komponenten-Trennung: Blank oder Komma [ 1 2, 3 ] nächste Zeile mit Vorschub oder Semikolon M = [ 11 12 13 M = [ 11 12 13; 21 22 23 ] 21 22 23 ]
Colon-Operator 2:3:13 2 5 8 11 M=[1:3; 4:6; 7:9]
spaltenweise Indexierung wie in Fortran # C M(2,3), M(:,2), M(2,:), M(end-1:end, [1 3]) size(M), length(M)
Vektoren sind Matrizzen mit nur einer Dimension n>1 Zeilenvektoren size 1xn , Spaltenvektoren size nx1
Skalare sind Matrizzen mit Dimension 1x1
5
computational geodynamics Goethe University of Frankfurt
Magisches Quadrat von Albrecht Dürer
6
computational geodynamics Goethe University of Frankfurt
Magisches Quadrat von Albrecht Dürer
7
computational geodynamics Goethe University of Frankfurt
Magisches Quadrat von Albrecht Dürer
Gleiche Summe von Zeilen, Spalten und Diagonalen
Prüfen !
8
computational geodynamics Goethe University of Frankfurt
Magisches Quadrat 34 DQ=[ 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 ]
sum(DQ(1,:)) Summe 1. Spalten, sum(DQ) Spaltensummensum(DQ') Zeilensummen, mit DQ' – Transponierte DQT Spiegelung an der Diagonalensum(diag(DQ)) Summe Diagonale, mit diag(), [DQii], i=1:n
sum(diag(fliplr(DQ))) Summe Gegendiagonale, mit fliplr() - Vertauschung Spalten links und rechts
Dür
er-Q
uadr
at
9
computational geodynamics Goethe University of Frankfurt
MatLab
Operatoren elementares Rechnen, arithmetische: ^ * / + - Prioritätsfolge ( ) vor ^ vor * / vor + - X=[1 2;3 4 ], Y=[5 6;7 8], X+Y, X*Y, elementweise X.*Y, X^2, X.^2 Transponierte X', Inverse inv(A), A/B entspricht A*inv(B) und A\B entspricht inv(A)*B Lösung von linearen Gleichungssystemen mit b=[11 12]' und x=A\b ! Prüfen
Logische Operatoren && || ~ Vergleiche > >= < <= == ~= liefern logische Ausdrücke, auch Matrizzen L=M<5
Ausgabe ; unterdrückt sie, fprintf, sprintf, disp ähnlich C format short, format long, format compact % - alles danach ist Kommentar 10
computational geodynamics Goethe University of Frankfurt
Paus
e
11
computational geodynamics Goethe University of Frankfurt
MatLab
Workspace enthält alle Variablen, who, whos
Variable Speichern, Löschen, Laden save gesamter Workspace auf matlab.mat in 'pwd', binär save filename a M auf Datei filename.mat, nur spez. Variable save file.asc M -ascii auf Datei file.asc, les- und editierbar clear, clear M, clear all load Wiederherstellung des gesicherten Workspace load filename existierende Daten werden überschrieben load filename M spez. Variable aus filename.mat laden N=load('file.asc') Daten müssen in Matrixform vorliegenIO – Ein- und Ausgabe von und auf Dateien fopen, fclose, fread, fwrite, fprintf, fscanf, fseek, ftell, ferror
12
computational geodynamics Goethe University of Frankfurt
MatLab
Kontrollstrukturen - Ablaufsteuerung Verzweigung if (k==13), disp('k brings misfortune'); end if () – elseif () – else – end if (1),... if (0), ... Fallunterscheidungen switch fall case 1 disp('do 1.Fall things') case {2,3} disp(' more then one case') case 13 disp(' bad luck case') otherwise disp('case not defined') end fall kann auch ein String sein
13
computational geodynamics Goethe University of Frankfurt
MatLab
Kontrollstrukturen if – switch – for – while, continue, break Schleifen for k=1:13 kseq=[ 12 1 7]; for k=kseq dosomething(k) end oder so: kseq=[12 1 7]; for k=kseq, … end
oder so: k=0; while (k<13) k=k+2; if (k>7), continue; end if (k>27), break; end k=k+1; end
14
computational geodynamics Goethe University of Frankfurt
MatLab
Kontrollstrukturen try & catch Abfangen von Fehlern try … Anweisungen … - bei Fehler Sprung zu catch - catch % Fehlerbehandlung … Anweisungen … end
Skript oder Funktion beenden return MatLab beenden exit
15
computational geodynamics Goethe University of Frankfurt
MatLab
Skripte, Functions mit Extension .m Starten mit Skriptname ohne Endung, muss im Pfad liegen Pfad: path, addpath(), rmpath(), pwd, cd, ls, dir, which … zu eigenen Skripten, Funktionen, Daten zu Toolboxen (Standard-MatLab, Erweiterungen z.B. Statistik, Mapping, Image Processing, PDE, Parallel Processing, ...)
Function-Kopf: function [result, out ]=dosomething(arg1,arg2) Der Dateiname sollte mit dem Funktionsnamen identisch sein (+ .m). Im Gegensatz zum Skript (Workspace ist global), sind die Variablen der Funktion lokal. Ende: return, end nargin, nargout liefern Argumentanzahl Erste %-Zeile wird von lookfor durchsucht, help dosomething liefert ersten %-Block. Vorsicht: Namen sind nicht reserviert: sin=5 überschreibt sin-Funktion.
16
computational geodynamics Goethe University of Frankfurt
MatLab
Intrinsische Funktionen: mathematische sin, cos, tan, exp, sqrt, abs, mean, std zeros, ones, eye, rand, randi, randn, ...und viele, viele mehr : help
matlab/general - General purpose commands.matlab/ops - Operators and special characters.matlab/lang - Language constructs and debugging.matlab/elmat - Elementary matrices and matrix manipulation.matlab/specmat - Specialized matrices.matlab/elfun - Elementary math functions.matlab/specfun - Specialized math functions.matlab/matfun - Matrix functions - numerical linear algebra ...
17
computational geodynamics Goethe University of Frankfurt
MatLab
intro < chol end function lu quit sprintf help > clc eps global macro qz sqrt demo = clear error grid magic rand startup [ & clg eval hess max rcond string ] | clock exist hold memory real subplot ( ~ conj exit home mesh relop sum ) abs contour exp ident meta rem svd . all cos expm if min return tan , ans cumprod eye imag nan round text ; any cumsum feval inf nargin save title % acos delete fft input norm schur type ! asin det filter inv ones script what : atan diag find isnan pack semilogx while ' atan2 diary finite keyboard pause semilogy who + axis dir fix load pi setstr xlabel - balance disp floor log plot shg ylabel * break echo flops loglog polar sign zeros \ casesen eig for logop prod sin / ceil else format ltifr prtsc size ^ chdir elseif fprintf ltitr qr sort
18
computational geodynamics Goethe University of Frankfurt
MatLabacosh demo hankel membrane print table1 angle demolist hds menu quad table2 asinh dft hilb meshdemo quaddemo tanh atanh diff hist meshdom quadstep tek bar eigmovie histogram mkpp rank tek4100 bench ergo hp2647 movies rat terminalbessel etime humps nademo ratmovie toeplitzbessela expm1 idft nelder readme trace besselh expm2 ieee neldstep residue translatebesseln expm3 ifft nnls retro tril blanks feval ifft2 null roots triu cdf2rdf fft2 info num2str rot90 unmkpp census fftshift inquire ode23 rratref vdpol citoh fitdemo int2str ode45 rratrefmovie versa cla fitfun invhilb odedemo rref vt100 compan flipx isempty orth rsf2csf vt240 computer flipy kron pinv sc2dc why cond funm length plotdemo sg100 wow conv gallery log10 poly sg200 xterm conv2 gamma logm polyfit sinh zerodemocorr getenv logspace polyline spline zeroin cosh ginput matdemo polymark sqrtm ctheorem gpp matlab polyval square dc2sc graphon mean polyvalm std deconv hadamard median ppval sun
19
computational geodynamics Goethe University of Frankfurt
MatLabaddtwopi buttap cov fftdemo freqz kaiser specplot bartlett butter decimate filtdemo fstab numf spectrum bilinear chebap denf fir1 hamming readme2 triang blackman chebwin detrend fir2 hanning remez xcorr boxcar cheby eqnerr2 freqs interp remezdd xcorr2 yulewalk
MatLab Version 7.3 (R2006b)
20
computational geodynamics Goethe University of Frankfurt
MatLab
2D Grafikeinfache abfallende Cosinus-Funktion: x=0:pi/36:*3*pi; y=2.5*cos(x).*exp(-0.1*x); plot(x,y) durchezogene blaue Linie plot(x), plot(y) ? plot(x,y,'r-o'), plot(x,y,'k:p') 'FMS' Farbe, Linientyp, Symbol' Farben: r g b m y c w k, Linientyp: -, --, :, .-, 'none' Symbol, Marker: + o * x s d v < > p h plot(x,y,'-s','LineWidth',3,'MarkerSize',24) mit ,'Property',Value, h=plot(x,y) mit Ausgabe des Handles des Grafikobjekts get(h) zeigt alle Eigenschaften set(h,'LineWidth',4) setz eine Eigenschaft u.a. Children, Parent - gca
21
computational geodynamics Goethe University of Frankfurt
MatLab
Grafikhelp gca get current axishelp gcf get current figurehelp gco get current object by mouse click
figure() öffnet ein Bildfenster für Grafik oder GUIComsol-Konsole hat Handle 0 und ist spezielles FensterWechsel: figure(fig_handle) Eigenschaften: get(gcf | fig_handle) Auswahl: Color, CurrentPoint, MenuBar, Name, Position, Units,
WindowButtonDownFcn, ButtonDownFcn, Children, HitTest, Visiblefclose, fclose(fig_handle), fclose all
22
computational geodynamics Goethe University of Frankfurt
MatLab
3D Grafikeine sich nach oben verjüngende Spirale: t=0:6/360:*5; r=exp(-t/3); x=r.*cos(t*2*pi); y=r.*sin(t*2*pi); z=t.*t*0.1; hp3=plot3(x,y,z); blaue Linienspirale set(hp3,'LineWidth',1,5) dicker title('\it{Himmelsspirale}') Titel xlabel('x(t) = e^{-t/3} cos(2\pit)') Achsenbeschriftung ylabel('y(t) = e^{-t/3} sin(2\pit)') y-Achse zlabel('z(t) = t^2/10') mit LaTeX view(3), view(2), view(30,15)
23
computational geodynamics Goethe University of Frankfurt
MatLab
Aufgabe
Gelerntes ausprobieren, Variationen davon in Skripte oderProgramme fassen und als m-File speichern. Und in einem Hauptskript die Programme zusammenfassenund starten.