Reading numbers from a string in MATLAB

I always have needs to find numbers from a formatted string using Matlab. For example, find the lats and longs for all the grid cells of a river basin based on a bunch of input files, something like (forcings_35.25_-100.75). Then in Matlab you have two ways to read these numbers out.

  • using ‘sscanf’. It’s kinda stupid that you can’t find the two numbers by
  • sscanf('forcings_35.25_-100.75','%s_%f_%f')

    instead, you will get an 1d array that contains 22 numbers, with each number representing a single character in that string. What you need to do is using

  • sscanf('forcings_35.25_-100.75','forcings_%f_%f')

    I guess the reason behind this is that sscanf can only output one numerical matrix that based on the first character it processes. So if you do

  • sscanf('35.25_-100.75_forcings','%f_%f_%s')

    you will get the first two number you want, followed by 8 numbers representing the string “forcings”.

  • Another way is to use “textscan”. I feel safer using this method.
  • A = textscan('forcings_35.25_-100.75','%s %f %f', 'Delimiter', '_')

    This way, you will end up getting a three cell array representing the three parts separated by “_” in the string. Then simply using cell2mat() to convert the numbers to regular array. To convert “forcings” to string, using

  • char(A{1})
Advertisements

Matlab built-in colors

Capture

to get RGB values for default Matlab color order, use

get(gca,'ColorOrder')

or use colormap to get values for any built-in style

rgb = colormap(parula(10)); % 10 is number of color

ArcGIS shape file plot in Matlab

ArcGIS shapes such as points and polygon, or even raster files can be plotted in Matlab. Here is an example of reading and plotting HUC4 polygons in Matlab.

First if read in the shape file that’s generated in ArcGIS

%read in shapefile
huc = shaperead('C:\HUC4.shp','UseGeoCoords', true, 'BoundingBox', [lonlim', latlim']);

then we get a struct like this, in which most of the columns are attribute table variables, with the first few columns showing the geometrical information about each polygon.

Capture

Sometimes the vertices are too many for each polygon, which makes the plotting process extremely slow. Here I am using a tool called DecimatePoly to reduce the total number of vertices 10 times less without making noticeable changes on the shape.

Next we will define the color of the polygon by one of the variables in the attribute table using makesymbolspec:

faceColors = makesymbolspec('Polygon',{'INDEX',[1 lenS],'FaceColor',color_att});
%lenS is the number of polygon
%color_att is a 3-column matrix of RGB triplets with length of LenS

Next is to create a map frame to plot on:

ax = usamap(latlim,lonlim); %plot frame using usamap as template 
axis off; framem on; gridm on; mlabel on; plabel on;
setm(gca,'MLabelLocation',10) %interval for meridians labeling
setm(gca,'PLabelLocation',5)  %interval for parallels labeling

Then plot the polygons

geoshow(ax, huc, 'SymbolSpec', faceColors);

When plotting points on the map, use scatterm

scatterm(lat,lon,s,c,'filled'); % s is vector defines the size of the dots
                                % c is RGB defines the color of the dots

untitled

Matlab meets Unix

1. running Matlab .m script in terminal without showing desktop (for batch running).

> know where the Matlab is installed. For example in my Mac the Matlab is installed in

/Applications/MATLAB_R2012b.app/bin

> call Matlab from anywhere that stores the script (test_script.m) you want to

run/Applications/MATLAB_R2012b.app/bin/matlab -nodesktop -nojvm -nosplash -r "test_script(arguments)"

2. compile Matlab .m scripts to executables.

> in Matlab GUI use Apps->Matlab complier
> in terminal use mcc -m test_script.m
to generate an executable file (test_script) and a shell script (run_test_script.sh) which is used to run the executable.
Then in terminal:

./run_test_script.sh /PATH/TO/MATLAB/ arguments

Note that the arguments will be passed to Matlab as strings. That means if they are numbers you need to add “str2num” in the code to convert them from strings to the numbers.

Matlab plot

Plotting in Matlab is a very big topic. Here I just want to share some plotting functions I’ve been using to produce the maps.

pcolor and imagesc

If we have a 4*4 matrix and want to plot it as a 2d surface, two functions (pcolor and imagesc) can be considered. But these two functions yield different results:

create a matrix:

A = hadamard(4);
A = 
1  1  1  1
1 -1  1 -1
1  1 -1 -1
1 -1 -1  1

The pcolor (A) will cut the last column and row then flip upside down before plot. That’s because the first cell (1,1) is considered as origin point (0,0) at lower left. So the plot looks like this (red is 1, blue is -1):

untitled

But the imagesc (A) will give the as-is plot:

untitled

Read txt in matlab

textread: read whole file;

dlmread: set the delimiter, set the reading range;

fgetl: read line by line;

e.g.

fid=fopen('xx.txt');
  for i=1:40;
    a=fgetl(fid);                             %read as string
    b(i,:)=(sscanf(a,'%f"))';             %convert to array
  end;
fclose(fid);
The output will be a “40*n” matrix.