github twitter email rss
Matlab
0001 Jun 1
4 minutes read

Matlab

% comments

Variables

  • ans - result of last calculation

Functions

  • help
  • whos
  • class()
  • isinf()
  • num2str()
  • disp()
  • strcmpi(, )
  • !dir


INF, NaN and other constants

pi
Inf
NaN
i
j

infinity = 1/0
    Inf
isinf(infinity)
    1
whos infinity

Numeric output formats

format longg;
format bank;
format hex;
format rat;

Characters and strings

str = 'I''m string';
    I'm string
a = 'hello'
b = 'world'
[a ',' b '!']
    hello, world!

Structures

person.name = ‘dmitry’;
person.age = 24;

functions handles

s= @sin
    s(pi/2)
        1

    sumOver3 = @(x,y) = (x+y)/3
    sumOver3(1,2)
        1

    incApply = @(x, y, f)f(x + 1, y + 1)
    incApply(2, 3, sumOver3)
        2.3333

conditionals

t = 20;
if t > 20
    disp('hot')
elseif
    dist('cold')
else
    disp('undefined')
end

cc = 46;
switch cc
    case 44
        disp(44)
    case 46
        disp(46)
    otherwise
        disp('otherwise')
end

for

sum = 0 
for i=1:500
    sum = sum + i
end

disp(sum)

exception

try
    disp(foo)
catch e
    disp(['oops!' e.message])
end

vectors

everything as array
x = 5 is really x = [5]

x = 42
whos x
x(2) = 24
whos x

adress = {132, 'boulevrd road'}
person = {21, 'name', adress}
person(1)
person{1}

row = [1 2 3 4]
column = [1;2;3;4]

oneToTen = 1:100
oneToHundredEach2 = 1:2:100
zeroToOneIn100Points =  linspace(0,1, 101)

2x2Matrix = [1 2; 3 4]
2x1MatrixOfZeros = zeros(2,1)
4x4Indetitymatrix = eye(4)
spy(4x4Indetitymatrix) %plot matrix

elementOn5 = oneToTen(5)
from5To10 = oneToTen(5:10)
from90toEnd = oneToTen(90:End)
firstFiveElementsIsReversed = oneToTen(1:5) = 5:-1:1

2x2Matrix(3)
2x2Matrix(2,2)
firstRow = 2x2Matrix(1,) 
secondColumn = 2x2Matrix(:,2)
stringFromAtoZ = 'a':'z'

sorting

matrix5x5WithRandom = magic(5);
sortedByColumn = sort(matrix5x5WithRandom);
sortedByRow = sort(matrix5x5WithRandom, 2);

firstRowElementsFrom1To2 = matrix5x5WithRandom(1,1:2)

x = [1 2]
y = [3 4]
[x y]
[x;y]

arrayOf25Elements = reshape(matrix5x5WithRandom, 1, 25);

transposition

x = [1 2; 3 4]

transpose(x)
x'

rowVector = (1:10)
columnVector = rowVector'

inverseMatrix = inv(x)
inverseMatrix = x^-1
identityMatrix = inverseMatrix * x

Elementwise Operators

a = reshape(1:4,2,2)
b= reshape(5:8,2,2)
a*b
a.*b


q0=100      % 100$
r=0.05      % interest rate
t = 1:10    % 10 years
q = q0 + (1+r).^t
plot(q)

Solving Systems of Equations

% x+y = 10
% x-y = 4
a = [1 1;1 -1]
b = [10;4]
linsolve(a,b)
a\b

Multidimensional Arrays

a = [1 2; 3 4]
a(:,;,2) = [5 6; 7 8]
whos a

a(1,2,1)

b = reshape(1:27, [3 3 3])

Functions

function [output_args] = FinctionName(input_args)
    function_body
end


function [x1, x2] = SolveQuadratic(a, b, c)
    disc = b*b - 4*a*c
    x1 = (-b + sqrt(disc))/(2*a);
    x2 = (-b - sqrt(disc))/(2*a);
end

File structure

%% Section title
% descriptive text

plotting

x = linspace(-10,10,101);
y = x .^ 3;
plot(x, y);

[x,y] = meshgrid(-10:0.5:10, -10:0.5:10);
z = sin(x) .* sinh(y);
surf(z);

x = linspace(-10,10,101);
y = sin(x);
plot(x,y, '-r')
plot(x,y, 'color', 'blue')

[x,y] = meshgrid(-10:0.5:10, -10:0.5:10);
z = sin(x) ./ cosh(y);
surf(z);
surf(x, y, z, x);
ezplot('x/gamma(x)')


figure
ezplot('x^2')
hold on
p = ezplot('x^3');
set(p. 'color', 'red');
hold off

figure
x = linspace(-10,10,101);
plot(x, sin(x));
hold on
plot(x, cons(x), '-r');
hold off
xlabel('x');
ylabel('${\sin x}, {\cos x}$', 'interpreter', 'latex');
l = legend('${\sin x}, {\cos x}$');
set(l, 'interpreter', 'latex');
set(l, 'location', 'north');


figure
subplot(2,2,1);
ezplot('x^2');
subplot(2,2,2);
ezplot('gamma(x)');
subplot(2,2,3);
ezsurf('sin(x)*cos(y)');
subplot(2,2,4);
ezplot3('sin(t)', 'cos(t)', 't', [0,]);

figure
ezplot('sin(x)')
grid on
oaxes

OOP

Value class

account.balance = 0;

Handle class

classdef Account < handle
    properties
        Balance = 0
    end

    events
        InsufficientFunds
    end

    methods
        function Deposit(obj, amount)
            obj.Balance = obj.Balance + amount;

        function Withdraw(obj, amount)
            if(amount <= obj.Balance)
                obj.Balance = obj.Balance - amount
            else
                notify(obj, 'InsufficientFunds');
                % disp('insufficient funds');
            end
    end
end

classdef BankManager
    methods (Static)
        function OfferOverdraft()
            disp('Would you like an overdraft');
        end

        function Watch(account)
            addlistener(account, 'InsufficientFunds', ...
                @(src, e) BankManager.OfferOverdraft());
        end
    end
end

a = Account;
a.Balance = 100;
a.Deposit(50);
a.Withdraw(10);
a.Withdraw(300);
BankManager.Watch(a);

Inheritance

classdef SmartAccount < Account
    properties
        State = AccountState.Open;
    end

    methods
        function Close(obj)
            if obj.State == AccountState.Closed
                disp('Error: account already closed.')
            else    
                obj.Withdraw(obj.Balance);
                disp('account closed');
                obj.State = AccountState.Closed;
            end
        end
    end
end

Enumertaions

classdef AccountState
    enumeration
        Open, Closed
    end
end

Back to posts


comments powered by Disqus