User Tools

Site Tools


matlab_cookbook

«TableOfContents(3)»

Database

Open a DB connection

postgres

#!highlight matlab
connection = database('mydb', 'username', 'password', 'org.postgresql.Driver', 'jdbc:postgresql://192.168.1.2:5432/my_database');

sqlite

#!highlight matlab
% establish variables
path = '/home/myhome/routes/';
file = 'routes_20110101.sqlite';
databaseName = ''; %leave blank
userName = ''; %leave blank
password = ''; %leave blank
driver = 'org.sqlite.JDBC'; %downloaded from http://www.xerial.org/trac/Xerial/wiki/SQLiteJDBC
databaseURL = sprintf('jdbc:sqlite:%s%s', path, file);

% create connection
conn = database(databaseName, userName, password, driver, databaseURL);

% test for successful connection
if isconnection(conn)
% fetch data etc.

If you receive an exception when fetching results

??? Java exception occurred:
java.lang.IllegalStateException: SQLite JDBC: inconsistent internal state
                at org.sqlite.RS.checkCol(RS.java:69)
                at org.sqlite.RS.getColumnCount(RS.java:423)

Error in ==> rsmd.get at 55
  n = 1:double(getColumnCount(d.Handle));

Error in ==> cursor.fetch at 162
                x = get(rs,{'ColumnName';'ColumnType'});

you will need to adjust the return type of the results for Matlab

#!highlight matlab
setdbprefs('DataReturnFormat','cellarray'); 

(See the Matlab documentation for details http://www.mathworks.com/help/toolbox/database/ug/setdbprefs.html)

Get Column Names

#!highlight matlab
query = 'select * from blah';
cursor = exec(connection, query);
fetch(cursor);
names = columnnames(cursor);

Date and Time

Convert date to String

#!highlight matlab
datestr(now, 'dd-mm-yy HH:MM:SS')

Current Date

#!highlight matlab
now()

Parse a Date

#!highlight matlab
str = '2010-05-03 20:30:00.0'

datenum(str) % ans = 734261.854166667
datevec(str) % ans =  2010           5           3          20          30           0

Figures

Formatting

Axis Labels

#!highlight matlab

plot(time,value);
xlabel('The Time');
ylabel('The Value');

Date Axis

#!highlight matlab
time = datenum(time_str); % convert time string to a serial number
plot(time, value); % plot
datetick('x', 'dd-mm-yy HH:MM:SS','keepticks'); % tell matlab to format the xaxis using the supplied date format

Legend

#!highlight matlab
hold on;
plot(x);
plot(y);
legend('X Values', 'Y Values');

Rectangle

#!highlight matlab
rectangle('Position', [x,y, width, height], 'FaceColor','r');

Regression Line

#!highlight matlab

plot(x,y, '.'); %plot data
           
% plot regression line
p=polyfit(x, y,1) % fit a polynom of degree 1 
regression_y = x* p(1)+ p(2); % if higher polynom degree is used add terms.. eg. for degree2 :   y = x.^2*p(1) + x*p(2) + p(3)
plot(x,regression_y,'r'); 

Scatterplots

Simple Scatter Plots

#!highlight matlab
scatter(q, v, 'filled')  % or plot(q,v)

Scatter plot with color coding

#!highlight matlab
scatter(q,v,50, relative_error,'filled') % Parameters: x,y,size of point, value to determine color
caxis([0, 1]);
colorbar()           

Tweaks

Disable annoying popup of plots

#!highlight matlab
    set(figure,'visible','off');

Java in Matlab

Use Java Classes from Matlab

. Long Article here: http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/f4863.html

Short story: there are two ways to expose java .jar files to matlab

  • adding them to a textfile: matlab\toolbox\local\classpath.txt
  • using the matlab command: javaaddpath

Afterwards a java class can be used with its fully qualified name (“java.lang.String”) or you can use imports ( _import java.lang.*_ or _import java.lang.String_ )

NaNs

Remove NaNs from vector

#!highlight matlab
x = x(~isnan(x));

Remove rows containing NaNs from matrix

#!highlight matlab
X(any(isnan(X),2),:) = [];

More for example here: http://www.mathworks.com/access/helpdesk/help/techdoc/data_analysis/f0-10104.html#f0-8511

Sorting

Sorting structs

To sort an array of structs by one value use

#!highlight matlab
[unused,order]  = sort({original_values(:).timestamp})
sorted_values = original_values(order)

Webservices

Calling a Webservice from Matlab

Very simple examples can be found here: http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/ref/createclassfromwsdl.html

Alas, real life is never simple. I was unable to find information on how to pass an array of custom objects to a webservice. Some time of googling and trial-and-error later I finally managed to get things working. Here is an example of how to access a webservice which takes an Array of Points ( each point has x and y coordinates) and a Date as parameters:

#!highlight matlab

% (!) Note that this is just an example on how to use a web service in Matlab.
% There are much more convenient wrapper functions available for this specific service!
%
% create the inputs

p1.x=16.38163;
p1.y=48.18769;

p2.x=16.35889;
p2.y=48.18088;

points.item=[p1 p2]; % this MUST be called "item" (sic!) or else matlab will create a wrong SOAP message!

time.item = {'2009-05-22T12:00:00'};

suggestions.item = {'Mit Strassenbahn'};

% Create and call the Webservice

createClassFromWsdl('http://10.101.21.217:8080/service?wsdl');
efa_service=EFAService;
getNetworkIds(server, points, time, suggestions)
matlab_cookbook.txt · Last modified: 2012/07/25 22:02 by mantis