Matlab/Tips

From mn/geo/geoit
Jump to: navigation, search

<rst> A collection of useful tips and tricks for Matlab

=====================================

There is also a `reminder <MatlabIntro>`_ for some Matlab commands

    • 0. Lauching matlab in command line mode**

- Type `matlab -nodesktop -nojvm` in your terminal. This makes it more manageable to use matlab during remote access. - Add this as an alias to your .bashrc file: `alias ml='matlab -nodesktop -nojvm'`. This saves you from typing long lines.

    • 1. Changing the color map**

- You can load a couple of useful colormaps that reside in the ~flexpart/matlab/ctb directory.

 cmap=load('rybmap3.ctb'); % read the colormap
 cmap=flipud(cmap); % flips the colormap, if required 
 colormap(cmap);    % set the new colormap

Nice colormaps include rybmap3.ctb, rybmap4.ctb, greyinv.ctb, precip.ctb,...

- To create a new colormap, run the colormapeditor in matab, define a colormap, an then save to a new *.ctb file

 colormapeditor % create your color settings
 cmap=colormap;
 save -ascii 'mycolormap.ctb' cmap
    • 2. Logarithmic colour bar**

- `How to add a logarithmic colorbar to figures in Matlab <http://www.mathworks.com/support/solutions/data/1-2H5IF9.html?solution=1-2H5IF9>`_

    • 3. Sparse matrices**

- Use `a=sparse(a)` to create a sparse matrix of `a`. Sparse matrices can be used like usual (with a few exceptions), but potentially use a lot less memory, and are handled faster during calculations.

    • 4. Workspace and memory demand**

- Type `whos` to get an inventory of all declared variables, their name, dimensions, byte size, and format. Can also be restricted to one variable as `whos a`.

    • 5. Using fortran in Matlab**

- `Writing fortran routines that can be called from Matlab <http://g95.sourceforge.net/howto.html#matlab>`_

    • 6. Optimising memory access**

- Preallocate arrays before accessing them in loops

`uninitialised arrays need to be reallocated with each extension of the array`

 N = 10e3;
 x=zeros(N,1); % preallocate array instead of implicit declaration
 x(1) = 1000;
 for k=2:N,
   x(k) = 1.05*x(k-1);
 end

- Store and access data in columns

`even faster is it to use sequential access` x(r), `then the processor can make full use of the memory cache`

 N = 2e3;
 x = randn(N);
 z = randn(N);
 for c = 1:N.   % Column first
   for r = 1:N, % Row next, stored at monotonically increasing memory locations
     if x(r,c) >= 0
       y(r,c)=x(r,c)
     end
   end
 end

- Avoid creating unnecessary variables

`every new variable must be allocated, consuming memory and time`

 N = 3e3;
 x = randn(N);
 x=x*1.2;  % calculation in-place instead of 'y=x*1.2'


</rst>