Monday, 3 December 2012

MATLAB/OCTAVE crash tutorial for programmers: Useful bits

In this post, I would like to give you a crash tutorial on the basics of  MATLAB ™ - GNU Octave (MO). They are not fully compatible but quite close in grammar. For differences see here. We will concentrate on the basic data structures and object manipulation that would help you to write useful code quickly.
  • Vectors/matrices and Indexing
    Vectors or vectorial operations are the core of MO
    >> A = [ 3 6 7 8 2];
    >> A(1:3); % range indexing will print values from index 1 to index 3
    >> A(4:end); % Last two values of this vector
    >> A > 4 % logical indexing; this will return logical vector, components satisfying the condition
    0 1 1 1 0
    >> A(A > 4)  % one can use this logical indexing directly to extract elements that satisfy the condition
    6 7 8

    A([2 3 4]) % positional indexing
    logInx = A>4
    A(logInx)
    6 7 8
    Let's define 3 by 3 matrix
    >> M = [ 1 3 4 ; 5 6 9 ; 2 3 4]
    >> M(:,1:2) % first two columns

  • Structures and Cells
    A structure definition can be performs as follows
    persons=struct();
    Fields can be defined after .
    persons.age=12; Further index can be assigned dynamically
    persons(2).age=32;
    persons(3).age=40; 
  • Functions
    Return vector with  function definition must be in a seperate file. For example here pov.m (in the working directory)

    function [ pov2, pov3] = pov(x)
      pov2= x^2; pov3 = x^3;
    end


    (pwd will tell you which directory you are working in. A return vector here is [pov2, pov3].

  • Function handles and apply functions
    To define new function ff with function handle
    it takes a structure xx and returns its field age value

    ff = @(xx) xx.age

    We can apply this function to each element of the structure,
    returning an array (vector)

    arrayfun(ff, persons)

  • Example Task:
    Lets align two vectors, meaning that we found matching indices and delete non matching ones. Here is the solution:

    p1 = [2    11    15    19    28    41    45    47    48    51];
    p2 = [2    11    31    36    41    45    51    60    68    71];
    [~,indexp1] = intersect(p1,p2);
    % if you use ~, it means don't assign anything
    [~,indexp2] = intersect(p2,p1);
    p1 = p1(indexp1);
    p2 = p2(indexp2);

No comments:

(c) Copyright 2008-2017 Mehmet Suzen (suzen at acm dot org)

Creative Commons Licence
This work is licensed under a Creative Commons Attribution 3.0 Unported License.