Matlab - Tips

From XennisWiki
Jump to: navigation, search

Tips for writing programs with the program Matlab.

Basics

Anonymous Function

Further information: MATLAB:Anonymous Function

% Define a anonymous function
myFunction = @(param1, param2) sqrt(param1)*param2;
% Call the function
myFunction(4, 2)

Plot

Advanced example: Matlab - Scripts#Plots, Matlab - Filterung EEG-Signal

Example with axis labels, a title and a legend

% sampleData1 = ...
% sampleData2 = ...
figure(1)
    plot(1:100, sampleData1, 'r-', 1:100, sampleData2, 'b.-')
    title('Title of the figure')
    xlabel('n')
    ylabel('Amount')
    legend('Sample data 1', 'Sample data 2', 'Location', 'northeast')

Example with multiple plot commands and custom line style

    % ...
    hold on
        plot(x, sampleData1, 'r--', 'LineWidth', 2)
        plot(x, sampleData2, 'b');
    hold off
    % ....

More options

    % ...
    grid on
    axis equal
    % ....

Subplot

Advanced example: Matlab - Scripts#Norms

figure
subplot(1, 2, 1) % 1 row, 2 columns, 1. plot
    % ...
    title('1. plot')
subplot(1, 2, 2) % 1 row, 2 columns, 2. plot
    % ...
    title('2. plot')

Output

Output string

disp('Hello World')
fprintf('value=%i, value=%g\n', myIntegerVariable, myFloatVariable)

Output into file

See also: Matlab - Log einlesen und darstellen

% 'wt': Write in text mode
fid = fopen('example.txt', 'wt');
fprintf(fid, '%s\n', my_string);
fclose(fid);

Diary

diary('output.txt');

% ...
disp('Test instance #1.');
% ...

diary off;

Assert

n = 10;
M = randperm(n);
assert(isequal(size(M), [1, n]), ...
    'expected argument M to be a (1xn vector');

Files

Read CSV file

Read a CSV file and skip the first line (use textscan for more options)

data = csvread('example.csv', 1)

Concat directory names

Construct the path mydir/anotherdir/

path = fullfile('mydir', 'anotherdir', filesep)

Iterate directories

Output all directory name in the directory mydir

mydir = dir('mydir');

for directory in mydir':
    if directory.isdir == 1
        disp(directory.name)
    end
end

Iterate files

Read all CSV files in the directory mydir

files = dir(['mydir', '*.csv']);
for file = files'
    data = csvread([path, file.name]);
end

Advanced

Set character encoding

feature('DefaultCharacterSet', 'UTF8')

Use symbolic values

Instead of compute with real value use symbolic ones:

syms t_1 t_2

A = [t_1 1; 1 1];
B= [1 1; 1 t_2];
A*B

Output

[ t_1 + 1, t_1 + t_2]
[       2,   t_2 + 1]

Use objects (classdef)

see Matlab - Object-oriented programming

See also