Matlab.md 12.1 KB
Newer Older
Aaron Erhardt's avatar
Aaron Erhardt committed
1
# Matrices
Aaron Erhardt's avatar
Aaron Erhardt committed
2

Aaron Erhardt's avatar
Aaron Erhardt committed
3
## Generate
Aaron Erhardt's avatar
Aaron Erhardt committed
4

Aaron Erhardt's avatar
Aaron Erhardt committed
5
### Manual
Aaron Erhardt's avatar
Aaron Erhardt committed
6
7
8
9
10
11
12
13
14

```matlab
A = [1 2 3; 4 5 6]

A =
     1     2     3
     4     5     6
```

Aaron Erhardt's avatar
Aaron Erhardt committed
15
### Zero
Aaron Erhardt's avatar
Aaron Erhardt committed
16
17

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
18
A = zeros(3)    % 3x3
Aaron Erhardt's avatar
Aaron Erhardt committed
19
20
21
B = zeros(3, 2) % 3x2
```

Aaron Erhardt's avatar
Aaron Erhardt committed
22
### Ones
Aaron Erhardt's avatar
Aaron Erhardt committed
23
24

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
25
A = ones(3)    % 3x3
Aaron Erhardt's avatar
Aaron Erhardt committed
26
27
28
B = ones(3, 2) % 3x2
```

Aaron Erhardt's avatar
Aaron Erhardt committed
29
### Eye (zeros with ones in the diagonal)
Aaron Erhardt's avatar
Aaron Erhardt committed
30
31

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
32
A = eye(3)    % 3x3
Aaron Erhardt's avatar
Aaron Erhardt committed
33
34
35
B = eye(3, 2) % 3x2
```

Aaron Erhardt's avatar
Aaron Erhardt committed
36
### Magic
Aaron Erhardt's avatar
Aaron Erhardt committed
37
38
39
40
41

```matlab
A = magic(3) % 3x3
```

Aaron Erhardt's avatar
Aaron Erhardt committed
42
### Random values (from 0 to 1)
Aaron Erhardt's avatar
Aaron Erhardt committed
43
44
45

```matlab
A = rand(3) .* 2 % 3x3 with values from 0 to 2
Aaron Erhardt's avatar
Aaron Erhardt committed
46
B = rand(3, 2)   % 3x2
Aaron Erhardt's avatar
Aaron Erhardt committed
47
48
```

Aaron Erhardt's avatar
Aaron Erhardt committed
49
### Normally distributed random values (σ = 1, µ = 0)
Aaron Erhardt's avatar
Aaron Erhardt committed
50
51

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
52
53
A = randn(3) .* 2   % 3x3 with σ = 2, µ = 0
B = randn(3, 2)     % 3x2
Aaron Erhardt's avatar
Aaron Erhardt committed
54
55
56
C = randn(3, 2) + 3 % 3x2 with σ = 1, µ = 3
```

Aaron Erhardt's avatar
Aaron Erhardt committed
57
## Modify
Aaron Erhardt's avatar
Aaron Erhardt committed
58

Aaron Erhardt's avatar
Aaron Erhardt committed
59
### Transpose
Aaron Erhardt's avatar
Aaron Erhardt committed
60
61
62
63
64

```matlab
T = A'
```

Aaron Erhardt's avatar
Aaron Erhardt committed
65
### Invert
Aaron Erhardt's avatar
Aaron Erhardt committed
66
67
68
69
70

```matlab
B = inv(A)
```

Aaron Erhardt's avatar
Aaron Erhardt committed
71
### Rotate
Aaron Erhardt's avatar
Aaron Erhardt committed
72
73
74
75
76

```matlab
B = rot90(A)
```

Aaron Erhardt's avatar
Aaron Erhardt committed
77
### Flip
Aaron Erhardt's avatar
Aaron Erhardt committed
78
79

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
80
B = flip(A)   % flip rows (top to bottom)
Aaron Erhardt's avatar
Aaron Erhardt committed
81
82
83
B = fliplr(A) % flip columns (left to right)
```

Aaron Erhardt's avatar
Aaron Erhardt committed
84
### Multiply
Aaron Erhardt's avatar
Aaron Erhardt committed
85
86
87
88
89

```matlab
C = A * B
```

Aaron Erhardt's avatar
Aaron Erhardt committed
90
### Element wise multiplication
Aaron Erhardt's avatar
Aaron Erhardt committed
91
92
93
94
95

```matlab
C = A .* B
```

Aaron Erhardt's avatar
Aaron Erhardt committed
96
## Access
Aaron Erhardt's avatar
Aaron Erhardt committed
97

Aaron Erhardt's avatar
Aaron Erhardt committed
98
### As row vector
Aaron Erhardt's avatar
Aaron Erhardt committed
99
100
101
102
103

```matlab
A(:)
```

Aaron Erhardt's avatar
Aaron Erhardt committed
104
### Get rows
Aaron Erhardt's avatar
Aaron Erhardt committed
105
106
107
108
109

```matlab
A(1, :) % row 1
```

Aaron Erhardt's avatar
Aaron Erhardt committed
110
### Get columns
Aaron Erhardt's avatar
Aaron Erhardt committed
111
112
113
114
115

```matlab
A(:, 1) % column 1
```

Aaron Erhardt's avatar
Aaron Erhardt committed
116
### Get diagonal
Aaron Erhardt's avatar
Aaron Erhardt committed
117
118

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
119
diag(A)       % main diagonal (top left to bottom right)
Aaron Erhardt's avatar
Aaron Erhardt committed
120
121
122
diag(flip(A)) % other diagonal (bottom left to top right)
```

Aaron Erhardt's avatar
Aaron Erhardt committed
123
## Linear equations
Aaron Erhardt's avatar
Aaron Erhardt committed
124
125
126
127
128
 
```matlab
x = A \ b % solves Ax = b
```

129
130
131
132
133
134
135
## Find indices

```matlab
i = find(A);        % find all nonzero elements
i = find(A > 1); 
i = find(A < 1, 5); % get the first five elements
```
Aaron Erhardt's avatar
Aaron Erhardt committed
136

Aaron Erhardt's avatar
Aaron Erhardt committed
137
# Images
Aaron Erhardt's avatar
Aaron Erhardt committed
138

Aaron Erhardt's avatar
Aaron Erhardt committed
139
## Load image
Aaron Erhardt's avatar
Aaron Erhardt committed
140
141
142
143

```matlab
img = imread('path_to_file')
```
144
145

### Show image
Aaron Erhardt's avatar
Aaron Erhardt committed
146
147
148
149
150

```matlab
imagesc(img)
```

151
### Color map
Aaron Erhardt's avatar
Aaron Erhardt committed
152
153
154

```matlab
colormap(gray()) % gray color map
Aaron Erhardt's avatar
Aaron Erhardt committed
155
colormap(M)      % where M 255x3 with values from 0 to 1
Aaron Erhardt's avatar
Aaron Erhardt committed
156
157
158
```


Aaron Erhardt's avatar
Aaron Erhardt committed
159
160
161
# Datatypes

## Struct
Aaron Erhardt's avatar
Aaron Erhardt committed
162
163

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
164
165
166
167
student.name = "TestStudent"                     % create
student.age = 24                                 % add field
student2 = struct('name', 'Student2', 'age', 23) % compact
disp(student.name)                               % print name
Aaron Erhardt's avatar
Aaron Erhardt committed
168
169
170
```


Aaron Erhardt's avatar
Aaron Erhardt committed
171
## CellArray
Aaron Erhardt's avatar
Aaron Erhardt committed
172

Aaron Erhardt's avatar
Aaron Erhardt committed
173
Array containing different data types
Aaron Erhardt's avatar
Aaron Erhardt committed
174

Aaron Erhardt's avatar
Aaron Erhardt committed
175
### Create
Aaron Erhardt's avatar
Aaron Erhardt committed
176
177

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
178
ca = { 'chars', 9.81, 1 } % 1x3 cell array
Aaron Erhardt's avatar
Aaron Erhardt committed
179
180
```

Aaron Erhardt's avatar
Aaron Erhardt committed
181
### Access elements
Aaron Erhardt's avatar
Aaron Erhardt committed
182
183

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
184
ca(1) % -> 'chars'
Aaron Erhardt's avatar
Aaron Erhardt committed
185
186
```

Aaron Erhardt's avatar
Aaron Erhardt committed
187
### Get length
Aaron Erhardt's avatar
Aaron Erhardt committed
188
189

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
190
length(ca)
Aaron Erhardt's avatar
Aaron Erhardt committed
191
192
```

Aaron Erhardt's avatar
Aaron Erhardt committed
193
194
195
196

## Table

### Properties
Aaron Erhardt's avatar
Aaron Erhardt committed
197
198

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
199
200
table.Properties
table.Properties.VariableNames{1} % first column name
Aaron Erhardt's avatar
Aaron Erhardt committed
201
202
```

Aaron Erhardt's avatar
Aaron Erhardt committed
203
### Access column by name
Aaron Erhardt's avatar
Aaron Erhardt committed
204
205

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
206
table.column_name % access column (as vector) with name "column_name"
Aaron Erhardt's avatar
Aaron Erhardt committed
207
208
```

Aaron Erhardt's avatar
Aaron Erhardt committed
209
### Get sub-table
Aaron Erhardt's avatar
Aaron Erhardt committed
210
211

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
212
table(:, 2) % second column as table
Aaron Erhardt's avatar
Aaron Erhardt committed
213
214
```

Aaron Erhardt's avatar
Aaron Erhardt committed
215
### Access values
Aaron Erhardt's avatar
Aaron Erhardt committed
216
217

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
218
219
table{1, 2} % row 1, column 2, note brackets!
table{:, 2} % column 2
Aaron Erhardt's avatar
Aaron Erhardt committed
220
221
```

Aaron Erhardt's avatar
Aaron Erhardt committed
222

Aaron Erhardt's avatar
Aaron Erhardt committed
223
## Strings
Aaron Erhardt's avatar
Aaron Erhardt committed
224

Aaron Erhardt's avatar
Aaron Erhardt committed
225
### Create
Aaron Erhardt's avatar
Aaron Erhardt committed
226
227

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
228
229
str = "Hello"
fromChar = string(text)
Aaron Erhardt's avatar
Aaron Erhardt committed
230
231
```

Aaron Erhardt's avatar
Aaron Erhardt committed
232
### Concatenate
Aaron Erhardt's avatar
Aaron Erhardt committed
233

Aaron Erhardt's avatar
Aaron Erhardt committed
234
235
236
237
238
239
```matlab
str2 = str + " World!"
```


## Character array
Aaron Erhardt's avatar
Aaron Erhardt committed
240

Aaron Erhardt's avatar
Aaron Erhardt committed
241
### Create
Aaron Erhardt's avatar
Aaron Erhardt committed
242
243

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
244
245
text = 'Hello'
fromStr = char(str)
Aaron Erhardt's avatar
Aaron Erhardt committed
246
247
```

Aaron Erhardt's avatar
Aaron Erhardt committed
248
### Concatenate
Aaron Erhardt's avatar
Aaron Erhardt committed
249
250

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
251
text2 = [text ' World!']
Aaron Erhardt's avatar
Aaron Erhardt committed
252
253
```

Aaron Erhardt's avatar
Aaron Erhardt committed
254
### Access characters
Aaron Erhardt's avatar
Aaron Erhardt committed
255
256

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
257
c = text(1) % first character
Aaron Erhardt's avatar
Aaron Erhardt committed
258
259
```

Aaron Erhardt's avatar
Aaron Erhardt committed
260
### Convert to number
Aaron Erhardt's avatar
Aaron Erhardt committed
261
262

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
263
str2num('2')
Aaron Erhardt's avatar
Aaron Erhardt committed
264
265
```

Aaron Erhardt's avatar
Aaron Erhardt committed
266
267
268
## Output

### Create formatted string
Aaron Erhardt's avatar
Aaron Erhardt committed
269
270

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
271
sprintf('value: %f', float_val)
Aaron Erhardt's avatar
Aaron Erhardt committed
272
273
```

Aaron Erhardt's avatar
Aaron Erhardt committed
274
### Print string
Aaron Erhardt's avatar
Aaron Erhardt committed
275
276

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
277
disp('Hello')
Aaron Erhardt's avatar
Aaron Erhardt committed
278
279
```

Aaron Erhardt's avatar
Aaron Erhardt committed
280
### Print formatted string
Aaron Erhardt's avatar
Aaron Erhardt committed
281
282

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
283
284
% use \n for newline, the 1 is for printing to stdout
fprintf(1, 'value: %d\n', 2)
Aaron Erhardt's avatar
Aaron Erhardt committed
285
286
287
288
289
290
291
292
```

# Save and load

## Workspace

```matlab
save file_name
293
save file_name a b c % only save a, b and c
Aaron Erhardt's avatar
Aaron Erhardt committed
294
295
296
297
298
299
300
301
302
303
load file_name
```

## Table

```matlab
table = readtable('file_name')
detectImportOptions('file_name') % return detected import options
```

Aaron Erhardt's avatar
Aaron Erhardt committed
304
305
306
307
308
309
## Matrix

```matlab
matrix = readmatrix('file_name') % like readtable but only values as matrix
```

Aaron Erhardt's avatar
Aaron Erhardt committed
310
311
312
313
314
315
316
## File

```matlab
file_handle =  fopen('file_name', 'rw') % open as readable and writable
fclose(file_handle)
```

Aaron Erhardt's avatar
Aaron Erhardt committed
317

Aaron Erhardt's avatar
Aaron Erhardt committed
318
319
# Polynomials

320
321
322
323
324
325
## Create polynomial from roots

```matlab
p = poly([1 -2 3]);
```

Aaron Erhardt's avatar
Aaron Erhardt committed
326
327
328
329
330
331
332
333
334
335
336
337
338
339
## Fit polynomial to points

```matlab
% x and y: coordinate values, deg: degree of polynomial
p = polyfit(x, y, deg);
```

## Calculate values

```matlab
% get y values for vector x and polynomial x
y = polyval(p, x);
```

340
341
342
343
344
345
346
347
348
349
350
## Multiply polynomials

```matlab
p3 = conv(p1, p2);
```

## Get roots

```matlab
r = roots(p);
```
Aaron Erhardt's avatar
Aaron Erhardt committed
351
352
353

# Graphics

Aaron Erhardt's avatar
Aaron Erhardt committed
354
355
356
## Plots

### Plot
Aaron Erhardt's avatar
Aaron Erhardt committed
357
358
359
360
361
362
363
364

```matlab
x = 1:10;
y = x.^2;
plot(y);    % automatic x-axis
plot(x, y); % custom x-axis
```

Aaron Erhardt's avatar
Aaron Erhardt committed
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
### Stairs plot

```matlab
stairs(x, y); % plot values as stairs
```

### Discrete values

```matlab
ffty = fft(y);      % fast-fourier transform
stem(x, abs(ffty)); % plot FFT
```

### Logarithmic

```matlab
loglog(x, y); % both axes are logarithmic
```

### Semi-logarithmic

```matlab
semilogx(x, y); % x-axes is logarithmic, y-axis is linear
semilogy(x, y); % x-axes is linear, y-axis is logarithmic
```

Aaron Erhardt's avatar
Aaron Erhardt committed
391
392
393
394
395
396
397
### Simple function plot

```matlab
fplot(@sin);           % default, from -5 to 5
fplot(@sin, [-pi pi]); % from -pi to pi
```

Aaron Erhardt's avatar
Aaron Erhardt committed
398
399
## Charts

Aaron Erhardt's avatar
Aaron Erhardt committed
400
401
402
403
404
405
406
### Histogram

```matlab
histogram(A)     % where A is a vector of values
histogram(A, 15) % place values in 15 groups
```

Aaron Erhardt's avatar
Aaron Erhardt committed
407
408
409
410
411
412
413
414
415
### Bar

```matlab
h = bar([1 2 4 8]);       % create bar chart
h.FaceColor = [0, 0.7 0]; % set properties
```

## Plot options

Aaron Erhardt's avatar
Aaron Erhardt committed
416
417
418
419
420
421
422
423
424
### Hold (keep previous plots)

```matlab
hold on
plot(...)
```

### Formatting

Aaron Erhardt's avatar
Aaron Erhardt committed
425
Markers
Aaron Erhardt's avatar
Aaron Erhardt committed
426
427
428
429
430
431
432
433

```matlab
plot(x, y, '.r');  % red dots
plot(x, y, 'or');  % red circles
plot(x, y, 'xr');  % red x
plot(x, y, '*r');  % red stars
```

Aaron Erhardt's avatar
Aaron Erhardt committed
434
Lines
Aaron Erhardt's avatar
Aaron Erhardt committed
435
436
437
438
439
440
441
442

```matlab
plot(x, y, '-');  % regular lines
plot(x, y, ':');  % dotted lines
plot(x, y, '--'); % dashed lines
plot(x, y, '-.'); % dashed and dotted lines
```

Aaron Erhardt's avatar
Aaron Erhardt committed
443
Colors
Aaron Erhardt's avatar
Aaron Erhardt committed
444
445
446
447
448

```matlab
plot(x, y, 'color', [0, 0.6, 0.2]); % RGB color
```

Aaron Erhardt's avatar
Aaron Erhardt committed
449
Line width
Aaron Erhardt's avatar
Aaron Erhardt committed
450
451
452
453
454

```matlab
plot(x, y, 'LineWidth', 2); % set line width to 2 px
```

Aaron Erhardt's avatar
Aaron Erhardt committed
455
Marker color
Aaron Erhardt's avatar
Aaron Erhardt committed
456
457
458
459
460

```matlab
plot(x, y, 'MarkerFaceColor', [0, 0.6, 0.2]); % RGB color of markers
```

Aaron Erhardt's avatar
Aaron Erhardt committed
461
Marker size
Aaron Erhardt's avatar
Aaron Erhardt committed
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485

```matlab
plot(x, y, 'MarkerSize', 7); % set marker size to 7 px
```

### Legend and title

```matlab
title('Title');

% number of names should match number and order of plots
legend('First', 'Second', 'Third');

% legend with specific location
legend('First', 'Second', 'Third', 'Location', 'northwest');
```

### Labels

```matlab
xlabel('\alpha'); % set x-label to α
ylabel('y');
```

Aaron Erhardt's avatar
Aaron Erhardt committed
486
487
488
489
490
491
### Axes

```matlab
axis([XMIN XMAX YMIN YMAX]); % set scaling of both axes
```

Aaron Erhardt's avatar
Aaron Erhardt committed
492
493
494
## Figures

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
495
496
fig = figure; % note: properties are case sensitive!
fig = gcf;    % get handle to current figure
Aaron Erhardt's avatar
Aaron Erhardt committed
497
clf;          % clear current figure
Aaron Erhardt's avatar
Aaron Erhardt committed
498
499
500
501
502
```

### Typical object hierarchy

```mermaid
Aaron Erhardt's avatar
Aaron Erhardt committed
503
504
505
506
graph TD
  Figure --> Legend
  Figure --> Axes
  Axes --> Lines
Aaron Erhardt's avatar
Aaron Erhardt committed
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
```

### Set color

```matlab
fig.Color = 'w';           % white
fig.Color = [1.0 0.5 0.0]; % RGB
```

### Plot handles

```matlab
h = plot(x, y);    % get handle
h.LineWidth = 1.3; % modify properties
h.Marker = '.';    % set marker
Aaron Erhardt's avatar
Aaron Erhardt committed
522
523
```

Aaron Erhardt's avatar
Aaron Erhardt committed
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
### Sub-plots

```matlab
fig = figure;
subplot(2, 3, 1); % 2x3 matrix of plots, select first plot
plot(x, y);       % first plot

subplot(2, 3, 2); % 2x3 matrix of plots, select second plot
loglog(x, y);     % second plot

subplot(2, 3, 4); % 2x3 matrix of plots, select fourth plot
semilogx(x, y);   % second row, first plot

subplot(2, 3, 6); % 2x3 matrix of plots, select last plot
semilogy(x, y);   % second row, third plot
```

Get handle

```matlab
handle = subplot(2, 3, 1);        % select first plot
handle.Children(1).LineWidth = 2; % get line from handle and change width
```

548
549
550
551
552
553
554
555
## 3-dimensional

### 3D-plot

```matlab
plot3(x, y, z);
```

Aaron Erhardt's avatar
Aaron Erhardt committed
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
### Surfaces

Generate grid

```matlab
% Generate grid from matrices with duplicate rows of x and duplicate columns of y
[X Y] = meshgrid(x, y); % Matrices with dimension length(x) x length(y)
mesh(X, Y)              % Plot mesh

Z = X.^2 - Y            % use (uppercase!) X and Y to calculate Z
mesh(X, Y, Z)           % Plot mesh with Z coordinate
```

Mesh surface plot

```matlab
mesh(X, Y)              % Plot mesh (using X and Y from meshgrid)

Z = X.^2 - Y            % use (uppercase!) X and Y to calculate Z
mesh(X, Y, Z)           % Plot mesh with Z coordinate
```

Surface plot
579
580

```matlab
Aaron Erhardt's avatar
Aaron Erhardt committed
581
surf(X, Y, Z)           % Similar to mesh but always with Z coordinate
582
```
Aaron Erhardt's avatar
Aaron Erhardt committed
583

Aaron Erhardt's avatar
Aaron Erhardt committed
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
# Functions

## Regular functions

### Definition

```matlab
% global function, always at the top of a file
function file_name()
    % code...
end

% local function
function FuncName()
    % code...
end
```

### Parameters

```matlab
function funcName(param1, param2)
    disp(param1); % print param1
    disp(param2); % print param2
end
```

Variable parameters

```matlab
function funcName(param1, param2, varargin)
% function takes at least two parameters
    
    for cnt = 1:length(varargin)
        arg = varargin{cnt}; % get one of the variable arguments
        if isnumeric(arg)    % only print numeric values
            disp(arg);       % print variable parameters
        else                 % ignore non-numeric values
            disp("Can't display non-numeric values");
        end
    end
end
```

### Return values

```matlab
function returnValue = duplicate(param)
    returnValue = [param param];
end

value = duplicate(2) % value = [2 2]

% multiple return values
function [returnValue1, returnValue2] = funcName(param1, param2)
    returnValue1 = param1;
    returnValue2 = param2;
end

[value1, value2] = funcName(2, 3) % value1 = 2, value2 = 3
```

### Documentation

```matlab
function funcName()
% This is a documentation comment
% Explain what your function does here

% This is a normal comment again
end
```

## Anonymous functions

### Get function handle

```matlab
handle = @sin
handle(1) % returns sin(1)
```

### Define anonymous function

```matlab
handle = @(param) 2 * cos(param * 2) % handle(1) returns 2*cos(2)
handle = @(x) exp(x-x.^2) - 0.5
```

## Function characteristics

### Zeros

```matlab
fzero(handle, 1) % find a zero value starting from 1
```

### Fit parameters

```matlab
id = @(is,ud)is*exp(ud/0.05)  % diode current
is = lsqcurvefit(id, 1e-10, u, i); % find ideal value for is to fit measured values u and i
```

688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
## Differential equations

### First order

```matlab
% transform the equation so that u' is separated
du = @(t,u) -u/0.1;           % u' = -u/0.1
U0 = 3;                       % start value
tspan = [0 0.5];              % time span
[t u] = ode45(du, tspan, U0); % calculate values
```

### Higher order

```matlab
% transform the equation so that y' = y1' and y'' = y2' are separated
%            y1' = y2     y2' = sin(100*t) - y1   - y2
dy = @(t,y) [      y(2) ;       sin(100*t) - y(1) - y(2) ]; 
% c)
[t y] = ode45(dy, [0 1], [1; 0]); % start at y1 = 1 and y2 = 0
```

### Options

```matlab
opts = odeset('absTol', 0.05); % set absolute error tolerance
[t y] = ode45(@pendfun, tspan, yNull, opts);
```

717
718
719
720

# Transfer functions

## Create
721
722

```matlab
723
G = tf([1 0], [2 0 0]);
724
725
```

726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
## Step response information

```matlab
S = stepinfo(G);
```

## Plot step response

```matlab
orstep(G);
step(G, 0.2);
```

## Plot bode diagram

```matlab
bode(G);
```

## Plot nyquist diagram

```matlab
nyquist(G);
```
750

Aaron Erhardt's avatar
Aaron Erhardt committed
751
752
753
754
755
756
# Control structures

## for-loop

```matlab
for cnt = 1:5 % cnt can be any row vector
Aaron Erhardt's avatar
Aaron Erhardt committed
757
    fprintf(1, '%d\n', cnt);
Aaron Erhardt's avatar
Aaron Erhardt committed
758
759
760
761
762
763
764
765
end
```

## while-loop

```matlab
cnt = 0;
while cnt < 5
Aaron Erhardt's avatar
Aaron Erhardt committed
766
    fprintf(1, '%d\n', cnt);
Aaron Erhardt's avatar
Aaron Erhardt committed
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
	cnt = cnt + 1;
end
```

## if-statement

```matlab
cnt = 0;
if cnt == 0
    disp('Zero');
elseif mod(cnt, 2) == 0
    disp('Even');
else
    disp('Odd');
end
```

Aaron Erhardt's avatar
Aaron Erhardt committed
784
Comparing vectors
Aaron Erhardt's avatar
Aaron Erhardt committed
785
786
787
788
789
790
791
792
793
794
795
796
797

```matlab
vec1 = [1 2 3];
vec2 = [1 2 4];

vec1 == vec2
%   1×3 logical array
%   1   1   0

if ~isequal(vec1, vec2)
    disp('Not equal')
end
```
Aaron Erhardt's avatar
Aaron Erhardt committed
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814

## switch-statement

```matlab
value = 4;
switch value
    case 1
        display("One");
    case 2
        display("Two");
    case 3
        display("Three");
    otherwise
        display("Other number");
end
```

Aaron Erhardt's avatar
Aaron Erhardt committed
815

Aaron Erhardt's avatar
Aaron Erhardt committed
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
# Performance

## Time measurment

```matlab
tic         % start time measurement
time = toc  % take time measurement
time2 = toc % take another time measurement (from same tic)
```

## Solving linear equations

```matlab
x = A\b;      % fast, because optimized by Matlab
x = inv(A)*b; % slow
```

## Pre-allocating vectors

```matlab
for cnt = 1:100    % inefficient, causes a lot of re-allocations
	a(cnt) = cnt;
end

b = zeros(1, 100);  % pre-allocating memory
for cnt = 1:100    
	a(cnt) = cnt;
end
```

### Real-world example

```matlab
x = 0:0.01:150;
y = zeros(size(x)); % initialized with zeros, same size as x

cnt = 1;
for i = x    
	y(cnt) = sin(i);
	cnt = cnt + 1;
end
857
```