MATLAB Cheatsheet

Matlab-Schnelleinf ̈uhrung, PDF, 3 Seiten

Formatting

Number

format, Set Command Window output display format

>> a = 1/3;
>> b = 0.001;

>> format short
a = 0.3333
b = 1.0000e-03

>> format shortE
a = 3.3333e-01
b = 1.0000e-03

>> format shortG
a = 0.33333
b = 0.001

>> format shortEng
a = 333.3333e-003
b = 1.0000e-003

>> format long
a = 0.333333333333333
b = 1.000000000000000e-03

>> format longE
a = 3.333333333333333e-01
b = 1.000000000000000e-03

>> format longG
a = 0.333333333333333
b = 0.001

Strings

Functions That Format Data into Text

  • compose — Write arrays of formatted data to an output string array
  • sprintf — Write formatted data to an output character vector or string scalar
  • fprintf — Write formatted data to an output file or the Command Window
  • warning — Display formatted data in a warning message
  • error — Display formatted data in an error message and abort
  • assert — Generate an error when a condition is violated
  • MException — Capture error informatio
str = sprintf('Hello, %d worlds!', 20)
disp(sprintf('Hello, %d worlds!', 20))

% write to Command Window
fprintf('%5d %5d %5d %5d\n', A(1:4))

% write to file
fileID = fopen('myfile.txt','w');
nbytes = fprintf(fileID,'%5d %5d %5d %5d\n', A(1:4))

Matrix

Erzeugung von Matrizen


>> C = [ 1 2 4 4 5; 6 7 8 9 10];
C =
     1     2     3     4     5
     6     7     8     9    10

>> size(C)
     2     5

>> length(C)
     5

=================================

>> E = [ 1 2 3 4 5; 2 3 4 5 6; 3 4 5 6 7; 4 5 6 7 8; 5 6 7 8 9]
E =
     1     2     3     4     5
     2     3     4     5     6
     3     4     5     6     7
     4     5     6     7     8
     5     6     7     8     9

>> E(3,2)
     4

>> E(3,(2:5))
     4     5     6     7

>> E((3:4),(2:5))
     4     5     6     7
     5     6     7     8

Plotting

plot(x-values, y-values);
loglog(x-values, y-values);
semilogx(x-values, y-values);

xlabel('\omega in Hz');
ylabel('H_d_B');

axis([x-min x-max y-min y-max]);

grid on;
grid off;

hold on;
hold off;

Default Argument

Default Arguments in Matlab

function f(arg1,arg2,arg3)

  if nargin < 3
    arg3 =   'some default'
  end

end

LaTex

set(groot, 'defaultAxesTickLabelInterpreter',   'latex');
set(groot, 'defaultLegendInterpreter',          'latex');
set(groot, 'defaultTextInterpreter',            'latex');

Object-Oriented-Programming (OOP)

Objektorientiertes Programmieren in MATLAB
Einführung in die Objekt-Orientierte Programmierung mit MATLAB

Object-Oriented Programming
Create a Simple Class
Class Components
Class Syntax Guide
Automatic Updates for Modified Classes
Handle Class Destructor
Class Constructor Methods

Object Oriented Programming in Matlab: basics

Value Class vs. Handle Class

How to modify properties of a Matlab Object
Comparison of Handle and Value Classes

Callbacks

Write Callbacks for Apps Created Programmatically
Class Methods for Graphics Callbacks
Listener Callback Syntax
Callback Execution
Create Function Handle (Procedural)

Overload Methods

How to overload user defined functions in Matlab?
Operator Overloading

Objects

Use a MATLAB Timer Object
timer class, Create object to schedule execution of MATLAB commands
Timer Callback Functions

Functions

integral, Numerical integration
num2str, Convert numbers to character array
patch, Create one or more filled polygons
roots, Polynomial roots (Nullstellen des Polynoms)
fzero, Root of nonlinear function

Array
setdiff, Set difference of two arrays

Variables
varargin, Variable-length input argument list
exist, Check existence of variable, script, function, folder, or class
varargin, Variable-length input argument list
nargin, Number of function input arguments

Nice Way to Set Function Defaults
How to support default parameter in MATLAB FUNCTION ?

function y = somefun2(a,b,opt1,opt2,opt3)
    % Some function with 2 required inputs, 3 optional.

    % Check number of inputs.
    if nargin > 5
        error('myfuns:somefun2:TooManyInputs', ...
            'requires at most 3 optional inputs');
    end

    % Fill in unset optional values.
    switch nargin
        case 2
            opt1 = eps;
            opt2 = 17;
            opt3 = @magic;
        case 3
            opt2 = 17;
            opt3 = @magic;
        case 4
            opt3 = @magic;
    end
end

function y = somefun2Alt(a,b,varargin)
    % Some function that requires 2 inputs and has some optional inputs.

    % only want 3 optional inputs at most
    numvarargs = length(varargin);
    if numvarargs > 3
        error('myfuns:somefun2Alt:TooManyInputs', ...
            'requires at most 3 optional inputs');
    end

    % set defaults for optional inputs
    optargs = {eps 17 @magic};

    % now put these defaults into the valuesToUse cell array, 
    % and overwrite the ones specified in varargin.
    optargs(1:numvarargs) = varargin;
    % or ...
    % [optargs{1:numvarargs}] = varargin{:};

    % Place optional args in memorable variable names
    [tol, mynum, func] = optargs{:};
    
end

Try/Catch and Exception
try, catch, Execute statements and catch resulting errors
Throw an Exception
throw, Throw exception
error, Throw error and display message

Complex number
real, Real part of complex number
imag, Imaginary part of complex number
conj, Complex conjugate
angle, Phase angle
abs, Absolute value and complex magnitude

isType
is, Detect state
isscalar, Determine whether input is scalar
ismatrix, Determine whether input is matrix
isnumeric, Determine if input is numeric array
isempty, Determine whether array is empty
isnan, Array elements that are NaN
iscell, Determine whether input is cell array
istable, Determine whether input is table

Symbolic Toolbox
fplot, Plot symbolic expression or function
subs, Symbolic substitution

Window
figure, Create figure window
gcf, Current figure handle
clf, Clear current figure window
groot, Graphics root object
findobj, Locate graphics objects with specific properties
set, Set graphics object properties
get, Query graphics object properties

set(0, 'CurrentFigure', figureHandle)
fig = get(groot,'CurrentFigure');

2D Plot
linspace, Generate linearly spaced vector
plot, 2-D line plot
scatter, Scatter plot
line, Create primitive line

3D Plot / Mesh
plot3, 3-D line plot
scatter3, 3-D scatter plot
quiver3, 3-D quiver or velocity plot
meshgrid, 2-D and 3-D grids
contour, Contour plot of matrix
fill3, Filled 3-D polygons
How can I plot a 3D-plane in Matlab?

Axis
gca, Current axes or chart
cla, Clear axes
subplot, Create axes in tiled positions
hold, Retain current plot when adding new plots
axis, Set axis limits and aspect ratios
xlim, Set or query x-axis limits
xlabel, Label x-axis
legend, Add legend to axes
daspect, Control data unit length along each axis
pbaspect, Control relative lengths of each axis
Control Ratio of Axis Lengths and Data Unit Lengths
Manipulating Axes Aspect Ratio

grid on;     % Nur grobe Linien einschalten
grid minor;  % Nur feine Linien einschalten

% Entweder
ax = gca;
ax.GridColorMode = 'manual';
ax.GridAlphaMode = 'manual';
ax.GridColor     = [0.0, 1.0, 0.0];
ax.GridAlpha     = 1.0;

ax.MinorGridColorMode = 'manual';
ax.MinorGridAlphaMode = 'manual';
ax.MinorGridColor     = [1.0, 0.0, 0.0];
ax.MinorGridAlpha     = 0.4;

% Oder
set(gca, 'GridColorMode', 'manual');
set(gca, 'GridAlphaMode', 'manual');
set(gca, 'GridColor', [0.0, 1.0, 0.0]);
set(gca, 'GridAlpha', 1.0);

p1 = plot(t1, y1);
hold on;
grid minor;
p2 = plot(t2, y2);

legend([p1, p2], 'sin(x)', 'cos(x)',...
       'Location','northwest',
       'Orientation','horizontal');
fig = figure(1);
ax  = fig.CurrentAxes;

% DOESN'T WORK!!
hold(ax,'on');

% Set gca and use 'current axis' (gca)
axis(ax)
hold on;

Round / Floor / Ceiling
floor, Round toward negative infinity
ceil, Round toward positive infinity
round, Round to nearest decimal or integer
fix, Round toward zero

Time and Date
clock, Current date and time as date vector
datetime, Create array based on current date, or convert from date strings or numbers
posixtime, Convert MATLAB datetime to POSIX time
datestr, Convert date and time to string format
datenum, Convert date and time to serial date number
Date and Time Arithmetic
datetime Properties

>> c = clock()
    2.0170    0.0050    0.0120    0.0160    0.0290    0.0050

>> fix(c)
        2017           5          12          16          29           4

>> t = datetime('now','TimeZone','local','Format','d-MMM-y HH:mm:ss Z')
   2017_05_12_16_35_19 (as datetime object)

>> t = datetime('now');
>> datestr(t, 'yyyy_MM_dd_HH_mm_ss')
2017_35_12_16_05_28

>> t = datetime('now');
>> unix_time = posixtime(t);
>> t = datetime(unix_time, 'ConvertFrom', 'posixtime');

>> num2str(posixtime(datetime('now')))
1494612053.581
>> num2str(posixtime(datetime('now')) * 1000)
1494611994358

Axis-Ticks
xticks, Set or query x-axis tick values (DOESN’T WORK!)
Specify Axis Tick Values and Labels

Camera
camva, Set or query camera view angle
campos, Set or query camera position
camzoom, Zoom in and out on scene

Lineare Algebra
linsolve , Solve linear system of equations given in matrix form
tril, Lower triangular part of matrix
triu, Upper triangular part of matrix
diag, Create diagonal matrix or get diagonal elements of matrix

Quaternion
quatmultiply, Calculate product of two quaternions
quatinv, Calculate inverse of quaternion
quat2rotm, Convert quaternion to rotation matrix
quatnormalize, Normalize quaternion
eul2quat, Convert Euler angles to quaternion
quat2eul, Convert quaternion to Euler angles
quat2tform, Convert quaternion to homogeneous transformation
tform2quat, Extract quaternion from homogeneous transformation

Euler
angle2dcm, Convert rotation angles to direction cosine matrix

Images / Bilder
imread, Read image from graphics file
imfinfo, Information about graphics file
imshow, Display image
image, Display image from array
imagesc, Display image with scaled colors
im2uint8, Convert image to 8-bit unsigned integers
rgb2gray, Converts the truecolor image RGB to the grayscale intensity image I

Radon Transformation
radon, Radon transform

Serial
serial, Create serial port object
instrfind, Read serial port objects from memory to MATLAB workspace
fopen (serial), Connect serial port object to device
readasync, Read data asynchronously from device
Serial Write and Read Data
Serial Events and Callbacks
Timeout, Waiting time to complete a read or write operation

File
fopen, Open file, or obtain information about open files
fwrite, Write data to binary file
fread, Read data from binary file
fclose, Close one or all open files
fprintf, Write data to text file

Regelungstechnik / Control System
step, Step response plot of dynamic system; step response data
stepDataOptions, Options set for step
tf, Create transfer function model, convert to transfer function model
zpk, Create zero-pole-gain model; convert to zero-pole-gain model
impulse, Impulse response plot of dynamic system; impulse response data
ss, Create state-space model, convert to state-space model

s       = tf('s');
I_Gs    = Ks / (T1 * s);
IT1_Gs  = Ks / (T1 * s^2 + s);

[  I_y,   I_t] = step(  I_Gs, Tend);
[IT1_y, IT1_t] = step(IT1_Gs, Tend);

Properties

Root Properties, Graphics environment and state information
Figure Properties, Control appearance and behavior of figure window
Chart Line Properties (plot)
Axes Properties
Text Properties
Legend Properties
Scatter Series Properties

Camera Properties

Low-Level Camera Properties
Low-Level Camera Properties

CameraViewAngle Specifies the field of view of the “lens.” If you specify a value for CameraViewAngle, MATLAB overrides stretch-to-fill behavior (see the “Aspect Ratio” section).
CameraViewAngleMode In automatic mode, MATLAB adjusts the view angle to the smallest angle that captures the entire scene. In manual mode, you specify the angle.
Setting CameraViewAngleMode to manual overrides stretch-to-fill behavior.
% disable the stretch-to-fill behavior

set(gca,'CameraViewAngleMode','manual');
set(gca,'CameraViewAngle',10);
set(gca,'DataAspectRatio',[1 1 1]);

daspect([1 1 1]);

%         X      Y      Z
win = [ -1, 1, -1, 1, -1, 1];
axis equal;
axis(win);

=== OR ===

camzoom(1);

camzoom sets the axes CameraViewAngle property, which in turn causes the CameraViewAngleMode property to be set to manual. Note that setting the CameraViewAngle property disables the MATLAB stretch-to-fill feature (stretching of the axes to fit the window). This may result in a change to the aspect ratio of your graph. See the axes function for more information on this behavior.

MATLAB Game Programming

Gaming in Matlab
MATLABTETRIS

Call by value vs. Call by reference

Does MATLAB pass parameters using “call by value” or “call by reference”?
Can MATLAB pass by reference?
Pass variable by reference to function

Leave a Reply

Your email address will not be published. Required fields are marked *