Crash course in MATLAB

SpinW runs in MATLAB and Python, but today we will be focusing on MATLAB.

The concepts.... Arrays, Indexing, Objects

Arrays - Numeric

They are created using square brackets – comma or space separation for columns in a row, semi-colon separation for new rows, higher dimensions using indexing / repmat command

1D arrays

w_1row = [1,2,3];
w_1col = [1;2;3];
w_1col_to_1row = [1;2;3]’;

2D arrays

w_rowcol = [1,2,3;4,5,6];

3D arrays

w3d = repmat(w_rowcol,[1,1,3])
w3d(:,:,1) = w_rowcol;  w3d(:,:,2) = w_rowcol+2;
Arrays - Strings

Creating Strings

my_string = ‘hello world’;

Strings arrays are concatenated similar to numeric arrays....

my_string2 = [my_string, ’ hello everyone’];
Arrays - Structured

Structure arrays provide a way of storing more general information, referenced by fields.


w = struct();
w.tom = [1,2,3];
w.dick = ‘hello world’;
w.harry = [4,5,6,7;8,9,10,11];
Arrays - Cells

Cell arrays are another generic data storage mechanism, with a matrix-like structure.


cell1 = {[1,2,3], ’hello_world’, [4,5,6;7,8,9]};
cell2 = {[1,23], ’hello_world’; [4,5,6;7,8,9], cell1};

Note that the cell array is described by a curly bracket, not a square bracket!

Indexing

Arrays can be indexed. Note that the ordering is the reverse to Python and indexes start from 1!.


w1 = [1,3,5,7]

So w1(3) = 5 etc.

wcell = {‘hello’,’world’,[1,2,3]}

So wcell{3} = [1,2,3] etc.

In 2D:

w2 = [1,2,3; 4,5,6]

So w2(2,3) = 6

w2(:,[1:2]) = [1,2;4,5]
w2(:,[1,3]) = [1,3;4,6]
                
Objects and methods

Objects are data structures with defined properties, and internal self-consistency checks.

  • Cell arrays, structure arrays etc. are examples of Matlab’s built-in objects.
  • You can define your own, which is what we have done with SpinW

You create a SpinW object with:

s = spinw();

Methods are the functions that work on defined objects.

SpinW has many methods. e.g.

s.plot()
Objects and methods

Getting help for objects and methods

To find all the methods working on an object, use the methods function which the name of the object class.

methods(spinw)

Get help if you already know the name of a particular method for an object class e.g. addatom:

help spinw/addatom
doc spinw/addatom
Getting help

Function help

For any function that starts with sw_* use:
help sw_*

SpinW class methods

for spinw class methods use:
help spinw.function_name.
For help on plotting commands, use:
help swplot.

Online Documentation

All help can be found on http://www.spinw.org or https://spinw.github.io/spinwdoc

Generic MATLAB help

The cheatsheet

Many of you might not have extensive experience in MATLAB, so a cheatsheet of common and useful commands might be helpful

I've found that the one on the MATLAB file Exchange to be quite useful.