You are here

Matlab - Reference

% Literatur: Einfuehrung in MATLAB (ELT3 - FH Hagenberg)
 
% MATrix LABoratory
 
% Hilfsfunktionen
    help                                % Ueberblick Funktionsgruppen
    help general                        % allgemeine Befehle
    help /                              % Operatoren und Sonderzeichen
    help <function>                     % Funktionsbeschreibung
    type <function>                     % Funktionsquellcode
    lookfor <Stichwort>                 % Stichwortsuche im Hilfetext
 
 
% Zahlendarstellung
    % alle Zahlen im Format: double precision
    % (1 Bit Vorzeichen, 11 Bit Exponent, 52 Bit Mantisse)
    a = 123
    b = -100.13
    b = -1.0013e2;                      % ; verhindert Ausgabe der Operation
 
    x = a + j*b                         % komplexe Zahl (j <=> i)
 
    Inf                                 % Unendlich
    NaN                                 % Not a Number
    pi
    realmax                             % groesste Zahl
    realmin                             % kleinste Zahl
 
 
% Operationen
    + - * ^ /                           % arithmetische Operationen
    .* .^./                             % elementweise Operationen
 
    x = A \ b                           % loest lineare Gleichungssysteme
    A*x = b
 
    == ~= < > <= >=                     % Vergleichsoperationen
    isequal()                           % Vergleich von Matrizen
    && || xor any all                   % logische Operatoren
    & | ~                               % logische bitweise Operatoren
 
    [1 2]' = [1; 2] =                   % Transponierte Matrix
        1
        2
 
    sin asin                            % Bogenmass
    sind asind                          % Grad
    -> cos tan cot sec csc
 
    exp                                 % Exponentialfunktion e^
    log log10 log2                      % Logarithmus (natürl., 10er, dual)
    sqrt
    abs angle complex conj imag real    % Funktionen fuer komplexe Zahlen
    fix floor ceil round                % Runden
    mod rem                             % Modulus
    sign                                % Vorzeichen
 
 
% Variablen
    who whos                            % Anzeige definierter Variablen
    clear                               % alle Variablen loeschen
    clear <variable>
 
    A = [1 2 3] = [1,2,3]               % Zeilenvektor
        1 2 3
    B = [1;2;3;4;5]                     % Spaltenvektor
        1
        2
        3
    C = [1 2 3;4 5 6]                   % Matrize
        1 2 3
        4 5 6
 
    A = 1:3:15                          % Nummer generieren
        1 4 7 10 13
    B = 1:4
        1 2 3 4
 
    A = linspace(6,8,5)                 % Intervall unterteilen
        6.00 6.50 7.00 7.50 8.00
    B = logspace(0,2,5)                 % Intervall logarithmisch
        1.00 3.16 10.00 31.62 100.00    % unterteilen 10^0, 10^2
 
    A = zeros(2,4)                      % Matrizen generieren
        0 0 0 0
        0 0 0 0
    B = ones(2,3)
        1 1 1
        1 1 1
    C = eye(3)
        1 0 0
        0 1 0
        0 0 1
    D = rand(2,4)
 
    A=[1 1 2 2;                         % Submatrizen
       3 3 4 4;
       5 5 6 6;
       7 7 8 8];
    B=A(2:3,2:4)
    B =
        3 4 4
        5 6 6
 
    A=[1 2 3 4 5 6 7 8 9;
       9 8 7 6 5 4 3 2 1];
    A(:,2:2:end)
    A =
        2 4 6 8
        8 6 4 2
    A(:,5:end)=[]                       % Elemente loeschen
    A =
        1 2 3 4
        9 8 7 6
    A(1:3,2:3)=ones(3,2)                % mit 1en fuellen
    A =
        1 1 1 4
        9 1 1 6
        0 1 1 0
 
    A = zeros(2,2,0);                   % Array dynamisch erweitern
    A(:,:,1) = zeros(2,2);              % -> Bedingung: Elemente mit
    A(:,:,2) = ones(2,2);               %               gleicher Groesse
 
 
% Vektorfunktionen
    length                              % Laenge eines Vektors
    max                                 % Element mit groessten Index
    min                                 % Element mit kleinsten Index
    sum                                 % Summe der Elemente
    prod                                % Produkte der Elemente
    any                                 % liefert 0, wenn alle Elemente 0
    all                                 % liefert 1, wenn kein Element 0
    mean                                % arithm. Mittelwert des Vektors
    sort                                % sortiert Vektor aufsteigend
 
    A' = transpose(A)                   % transponierte Matrix
    A.' = ctranspose(A)                 % konjugiert komplex transponiert
    fliplr(A)                           % vertikale Spiegelung
    flipud(A)                           % horizontale Spiegelung
    rot90(A)                            % Drehung
    repmat(A,z,s)                       % zxs Blockmatrix aus A
    reshape(A,z,s)                      % Matrixdimensionen aendern
    diag(A,k)                           % k-te Nebendiagonale
 
    eig                                 % Eigenwert, Eigenvektor
    inv                                 % inverse Matrix
    expm, sqrtm                         % Matrix-Exponential, -Wurzel
    poly                                % charakteristische Polynom
    det                                 % Determinante
    size                                % Matrixdimension
    norm                                % Norm einer Matrix oder eines Vektors
 
 
% Zeichenketten
    a = 'Z'
    char, double                        % Umwandlung
    strcat str2mat strcmp upper lower   % Funktionen
    ischar isletter isspace             % logische Funktionen
 
    A = 'string';                       % String erweitern
    A = [A 'string2'];
 
 
% Dateiverwaltung
    pwd what cd type delete dir ls rmdir mkdir copyfile movefile fileattrib
    save <Dateiname> <Variablenliste>   % Variablen speichern
    load <Dateiname>                    % Variablen laden
        -ascii                          % im Textformat gespeichert
 
    fid = fopen(filename, modus)
        = -1                            % falls Datei nicht existiert
        'r'     % read
        'w'     % write
        'a'     % append
    [A, count] = fread(fid, size, precision)
        % size      - angegebene Anzahl an Daten
        % precision - Binaerformat ('int16', 'int32', 'float32', 'float64')
    count = fwrite(fid, A, precision)
    position = ftell(fid)               % Position einer Datei ermitteln
    status = fseek(fid, offset, origin) % Position anpassen
                                        % (origin: 'bof', 'eof')
    count = fprintf(fid, format, A, ...)% formatiertes Schreiben
        %c      % einzelnes Zeichen
        %d      % Dezimaldarstellung
        %u      % Dezimaldarstellung (unsigned)
        %e      % Exponentialdarstellung
        %f      % Fliesskommadarstellung
        %s      % Zeichenkette
        %x      % Hexadezimaldarstellung
        \n \b \r \t \\
    [A, count] = fscanf(fid, format, size)  % formatiertes Lesen
    fclose(fid)
 
 
% Scripts
    pause                               % auf Tastendruck warten
    pause(n)                            % n Sekunden warten
 
    if expression                       % bedingte Anweisung
        statements
    elseif expression
        statements
    else
        statements
    end
 
 
    switch switch_expr                  % switch Anweisung
        case case_expr,
            statement, ..., statement
        case {case_expr1, case_expr2, case_expr3,...}
            statement, ..., statement
            ...
        otherwise,
            statement, ..., statement
    end
 
 
    for variable = expr                 % for Schleife (zahler = n:1:10)
        statement, ..., statement
    end
 
 
    while expression                    % while Schleife
        statements
    end
 
 
% Funktionen
    % in .m Datei gespeichert
    % Funktionsname sollte Namen entsprechen
    % Hilftext startet unterhalb der 1. Zeile
    % Variablen sind lokal gueltig
    function[Rueckgabeliste] = Name(Parameterliste)
 
    nargin                              % Anzahl Eingabeargumente
    nargout                             % Anzahl Ausgabeargumente
    exist                               % existiert Variable/Funktion
    varargin                            % Eingabepar.liste unbest. Laenge
    varargout                           % Ausgabepar.liste unbest. Laenge
 
    global                              % Variable global definieren
 
 
% Grafiken
    plot(x,y)                           % Polygonzug mit den Knoten (xk,yk)
    plot(y) = plot(1:length(y),y)
    plot(x,y,s)                         % Stilparameter s
        % Punkttypen: .,o,x,+,*,s,d,v,^,<,>,p,h
        % Linientypen: -,:,-.,--
        % Farben: b,g,r,c,m,y,k
        % Beispiel: plot(x,y,'c+:')
    plot(x1,y1,s1,x2,y2,s2,...)         % mehrere Linien
 
    % Achsensystem
    axis([xmin xmax ymin ymax])         % Grenzen des Achsensystems setzen
    axis on, axis off                   % Achsensystem ein- und ausschalten
    axis auto, axis manual              % autom. Anpassung ein-/ausschalten
    axis equal                          % gleiche Laengeneinheiten
    axis tight                          % an Daten angepasster Ausschnitt
    axis image = axis equal, axis tight
    axis square                         % quadratischer Ausschnitt
    axis fill                           % Ausfuellen des Bildfensters
    grid on, grid off                   % Gitterlinien ein- und ausschalten
    box on, box off                     % Achsensystem im Box-Format
    pbaspect([x,y,z])                   % Seitenverhaeltn. des Achsensystems
    view(az,el)                         % Blickwinkel einstellen (in Grad)
 
    % Beschriftungen
    title                               % Ueberschrift
    xlabel, ylabel, zlabel              % Beschriftung der Achsen
    legend                              % Legende anfuegen
    text                                % Text in der Grafik
    colorbar                            % Farblegende
 
    % mehrere Grafiken
    hold on                             % in einem Achsensystem
    subplot                             % in einem Fenster
    figure                              % in unterschiedlichen Fenstern
    figure(figurenumber)                % Umschalten zwischen Fenstern
    clf, cla                            % Grafik loeschen
    close(figurenumber), close all      % Fenster schliessen
 
    % Beispiel 1
    t = 0:0.01:10;
    x1 = exp(-2*t).*cos(5*t);
    x2 = exp(-2*t).*sin(5*t);
    figure(1), clf
    plot(t,x1), grid
    hold
    plot(t,x2,'.g:')
    hold
    axis([0,5,-1,1])
    xlabel('t [s]')
    ylabel('Voltage [V]')
    legend('Funktion 1','Funktion 2')
    title('Darstellung von Funktionen')
    pause
 
    % Beispiel 2
    d = 0.1; wk = 1e4;
    w = logspace(1,6,1000);
    s = j*w;
    G = 1./(1+2*d*(s/wk)+(s/wk).^2); % Transfer function
    figure(2), clf
    subplot(211)
    semilogx(w,20*log10(abs(G))), grid
    ylabel('|G(j\omega)| [dB]');
    title('Bodediagramm für G(s)');
    subplot(212);
    semilogx(w,180/pi*angle(G)), grid
    xlabel('\omega [s^{-1}]');
    ylabel('\angle G(j\omega) [°]');
    % Find maximum
    [max_abs_G, i] = max(20*log10(abs(G)));
    fprintf('\n')
    fprintf('Max(abs(G)) in dB: %g\n', max_abs_G)
    fprintf('bei w = %g\n', w(i))
    pause
 
    % Beispiel 3
    x = 1:0.1:10;
    y=exp(x);
    figure(3), clf
    semilogy(x,y)
    grid
 
 
% Symbolic Math Toolbox
    % ermoeglicht Arbeiten mit symbolischen Variablen
    syms x y
    e = (1+x)^4/(1+x^2)+4/(1+x^2)
    pretty(e)
           4
    (1 + x)      4
    -------- + ------
          2         2
     1 + x     1 + x
 
    % Vereinfachungen
    simplify, expand, factor, collect
    simple                      % Search for shortest form
    numden                      % Numerator and denominator
    horner                      % Nested polynomial representation
    subexpr                     % Rewrite in terms of subexpressions
    coeffs                      % Coefficients of a multivariate polynomial
    sort                        % Sort symbolic vectors or polynomials.
    subs                        % Symbolic substitutionify(e)
 
    % grafische Darstellung von Funktionen
    syms x
    ezplot(exp(-x*x/2),-5,5); grid;
 
    % sonstige Funktionen
    taylor, diff, int, laplace, ilaplace, dsolve