Color Reference

plnPlain text
str"String content"
kwdKeyword
com// Comment
typTypeName
litLiterals: 42, 3.14
punPunctuation ;,:.
opn{open bracket
cloclose} bracket
tag<Markup tag name>
atn<Markup attribute-name="">
atv<Markup attribute="value">
decDeclaration
varVariable name
funFunction name
idntidentifier
scmd!system command
prmpt>> command prompt
err??? Error message
wrnWarning: message
prn([{parentheses}])
tpstranspose x'
lcntline ... continuation

MATLAB

Data Types


v = [1,2,3;4,5,6];
v(v==4) = 0;

s = struct('key',1, 'key2','string');
s.key = 2;

C = cell(1,2);
C{1,1} = 0:9;

double(1)
single(1)
uint8(1)
int8(1)

A = [B, eye(2), [1 2; 3 4]]

s(4,2).field = 'val'
val = s(1,2).(fname)

C = {[1.2 3], magic(4), '5'}
C{1,3}

fhandle = @sin;
func = @(x,y) x+y;

Strings and Transpose


plot(data');
legend(labels)

str = 'asdasd';     % this is a string
str = 'asdas';
str = 'sdasd''sdasd';

str = ['one' 'two' 'three'];
str = strcat('one', 'two', 'three');

% matrix transpose
M = rand(3,3)';
x = M.';
x = [10 20; 30, 40]';
disp(x')
fprintf('%d\n', x(:)')      % with comment
{1,2}'                      % another comment

chr = 'abcdefghij';
expr = '(?@disp(sprintf(''starting match: [%s^%s]'',$`,$'')))g';
regexp(chr, expr, 'once');

str = ['hello' name '!']
str = ['hello' 'world']
str = ['hello''world']
str = ['hello' [] 'world']
str = ['hello' '' 'world']

Line Continuation


[1 20; ...
30 4]

['gdgsd'...
'sdfs']

{...
'sdasd' ;
'asdsad'}

% valid
str = sprintf('Some value %s is %d', ...
    name, val);
str = ['This is ' ...
    'allowed'];

% not valid
str = 'this is not ...
    allowed';

x = 1 + 2 ...
    - 3;

x = [1.23...
4.56];

Line Continuation and Comments


x = a + ...  % comment one
    b - ...  comment two
    42;      % comment three

plot(x, ... this is a comment
     y)

plot(x, y, ...
    'LineStyle','-', ...
    ... 'LineWidth',2, ...  % this whole line is commented
    'Marker','o')

plot(x, y, ...
    'LineStyle','-', ...
%   'LineWidth',2, ...  % this whole line is commented
    'Marker','o')


Shell Escape


!touch file.txt

Command Prompt and Code Output


% compact
>> 1+1
ans =
     2

% loose
>> 1+1

ans =

     2

Functions


NET.addAssembly
NET.addAssembly('')

a = struct();
a.disp = [1,1,1];
a.disp(1)
a.disp'
(a.disp)'
disp(a)

Keywords


function ret = fcn(in)
    ret = sum(in.^2);
end

function [varargout] = func(varargin)
    disp(varargin')
end

classdef MyClass < handle
    properties (SetAccess = private)
        x = 0;
    end
    methods
        function this = MyClass(varargin)
            this.x = 9;
        end
    end
end

classdef Bool < logical
   enumeration
      No  (0)
      Yes (1)
      Off (0)
      On  (1)
   end
end

classdef (ConstructOnLoad) MyEventData < event.EventData
   properties
      val = 0;
   end
   methods
      function ev = MyEventData(value)
         ev.val = value;
      end
   end
end

classdef SimpleEventClass < handle
   events
      Overflow
   end
   methods
      function setProp(obj, value)
         if (value > 10)
            notify(obj, 'Overflow', MyEventData(10));
         end
      end
   end
end

for i=1:10, disp(i), end

global x y
persistent z w

x = [];
parfor i=1:10
    x(i) = i;
end

parpool(2)
spmd
  q = magic(labindex + 2);
end
delete(gcp)

true ~= false
inf, nan, eps, pi, i, j
nargin, nargout, varargin, varargout

if x==1
    true
elseif
    false
else
    return
end

while true
    continue
    break
end

try
    error('aa:aa', 'asdasd')
catch ME
    warning(ME)
end

switch x
    case 1
        disp(1)
    otherwise
        0
end

Tilde


[~,idx] = min(x)
~x
x~=y

Colon


x = 1:10
x = 1:2:10
x = A(1:5,:)
x = A(:)
x(:) = rand(3,4)

Operators


A+B
+A
A-B
-A
A*B
A.*B
A^B
A.^B
A\B
A.\B
A/B
A./B
A'
A.'

A>B
A>=B
A<B
A<=B
A==B
A~=B
A&B
A|B
~A

Number Literals


1
1.
.1
1.0
-1
-1.
-.1
-1.0
+10
+01.
+.1
+1.0
1e1
1e-1
1.e1
1.e-1
1.0e1
1.0e-1
.1e1
.1e-1
-.1e+1
+1.e-1

1i
.10j
-1.001i
+1e-100j
-.10e-01i

Unary vs. Binary Operators


1+1
1+ 1
1 +1
1 + 1
+1+1
+1+ 1
+1 +1
+1 + 1

Spaces


7 -2 +5
7 - 2 + 5

[7 -2 +5]
[7 - 2 + 5]

% error
not_valid = [1 2 zeros...
(1,3)]

% error
not_valid = [1 2 zeros (1,3)]

% valid
zeros(1,3)
zeros (1,3)

Comments


% % comment % %
x = 1;
   % comment
x = 2;
% comment
x = 3;
%# comment
x = 4;
%% comment
x = 5;
%#x = sum(x);
x = 6;
x = 7;  % comment

Block Comments


%{
block comment
%}

%{
%}

%{

%}

%{
1
2
%}

%{
% sdf {}
sdf
%asda{}
sfds
%}

    %{
dsf
        %}

%{%}

%{ zzz=10; %}

%{%x=10;%}

%{  x
a=10;
%}

%{
%a=10;
%}   x

Nested Block Comments


% nested block comments fail
%{
dfsdf
%{
xxx
%}
dfsdf
%}

% fails here!
%{
x=10;
%%{
%%}
y=20;
%}

Errors and Warnings


% MATLAB R2011a
>> dontexist(1)
??? Undefined function or method 'dontexist' for input arguments of type 'double'.

>> diag(1,1,1)
??? Error using ==> diag
Too many input arguments.

>> error('a:a','a')
??? a

>> warning('a:a','a')
Warning: a

% MATLAB R2011b
>> dontexist(1)
Undefined function 'dontexist' for input arguments of type 'double'.

>> diag(1,1,1)
Error using diag
Too many input arguments.

>> error('a:a','a')
a

>> warning('a:a','a')
Warning: a

Command vs. Function Syntax


cd ..
cd ..\folder

dir *.m
dir('*.m')
dir('/path/to')
dir('C:\path\to')

whos('var*')
whos var*
whos *var
whos var*ble

whos -file aa.mat X
whos('-file','aa.mat', 'X')

load file.mat
load('file.mat')

isequal A A
isequal('A','A')

disp hello
disp('hello')
disp 'hello world'
disp('hello world')


Octave


# octave specific comments

## comments
## in Octave

#!assert(sin(0)==0)
#!error sin()

#{
block
comment
#}

% double-quoted strings
str = "hello world";

% strings with escaping
str = "double-quotes strings with \"escaping\" backslashes";

% variable names
a = 1;
_a = 2;
__somethgin_reserved = 3;

_s = struct('_a',1);
disp(_s._a)

% increment/decrement
x++; ++x;
x+=y; x-=y; x*=y; x/=y; x^=y;
x.+=y; x.-=y; x.*=y; x./=y; x.^=y;

% index into rhs
x = magic(5)(2,3);

% exponentiation
y = x^2;
y = x**2;

% logical not
notEqual = (x != y);
negateOp = !x;

% printf/fprintf
printf('hello world\n');

% whitespace
[0 1]'   % works in MATLAB and Octave
[0 1] '  % works only in Octave (fix')

% line continutation
rand (1, ...
      2)
rand (1,
      2)
rand (1, \
      2)

% strings
str = ['this is a ', \
    'string'];
str = 'this is a \
    long text';


% strings
str = "aaa\
bbb";                  % ==> aaabbb
str = ['aaa' ...       % ==> aaabbb
'bbb'];
str = ["aaa" ...       % ==> aaabbb
"bbb"];
str = 'aaa '' bbb';    % ==> aaa ' bbb
str = "aaa "" bbb";    % ==> aaa " bbb
str = "aaa \" bbb";    % ==> aaa " bbb
str = "aaa \n bbb";    % ==> aaa {NewLine} bbb
str = 'aaa "ccc" bbb'; % ==> aaa "ccc" bbb
str = "aaa 'ccc' bbb"; % ==> aaa 'ccc' bbb
str = 'aaa " bbb';     % ==> aaa " bbb
str = "aaa ' bbb";     % ==> aaa ' bbb
str = "aaaa
bbb";                  % ==> syntax error

% line continuation
x = [
1
2];
x = [1
2];
x = [ ...
1
2];
x = [
1 ...
2];
x = [
1;
2];
x = [1;
2];
x = [1; ...
2];
x = [1 ...
2];

% hex notation
x = hex2dec('F0');
x = 0xF0;

% packages
pkg install image
pkg load image

% command prompt
octave:1> function str = greet(name)
>   ## Say hello
>   str = ["Hello ", name];
> end
octave:2> greet("Me")
ans = Hello Me

% keywords
for i=1:2
    disp(i)
endfor

while true
    if rand() > 0.5
        break;
    endif
endwhile

function fcn()
    disp('hello')
endfunction

switch x
    otherwise
endswitch

x = 0;
do
    x += 1;
until (x == 10)

unwind_protect
    % body
unwind_protect_cleanup
    % cleanup
end_unwind_protect

parfor i=1:10
    disp(i)
endparfor

classdef MyKlass
    properties
        x
    endproperties

    events
        ev
    endevents

    enumeration
        A
    endenumeration

    methods
        function m()
        endfunction
    endmethods
endclassdef

try
    % body
catch
    % cleanup
end_try_catch


C/C++


#include "stdio.h"
#include "stdlib.h"

/* main function */
int main() {
    // comment
    int x = 10;
    fprintf("x = %d\n", x);
    return 0;
}

Python


import numpy as np

def fcn(x):
    """
    some function
    """
   return "hello"

# call function
print fcn(1)