Showing posts with label Matlab. Show all posts
Showing posts with label Matlab. Show all posts

Friday, August 29, 2014

Convert Epoch Unix Time to Normal Date and Time in Matlab

Suppose, you start with a vector time_unix, then:


time_unix = 1339116554872; % example time
time_reference = datenum('1970', 'yyyy'); 
time_matlab = time_reference + time_unix / 8.64e7;
time_matlab_string = datestr(time_matlab, 'yyyy mm dd HH:MM:SS.FFF')

    time_matlab_string =

    2012 06 08 00:49:14.872

Some notes:

1) 8.64e7 is number of milliseconds in a day.
3) Matlab does not apply any time-zone shifts, so the result is the same UTC time.

Sunday, July 20, 2014

Plot on Specific Figure in Matlab

You might be interested to have different plots in seperate figures in your code. when you create a figure make sure you assign it to a handle:
fig1=figure(1) 
fig2=figure(2) 

Then later in your code when you want to plot that particular figure. first make that figure your current figure:

 figure(fig1)  
 subplot(2,1,1)  

then continue with your code and and for the other figure again change to that figure:



 figure(fig2)  
 plot(x)  

Wednesday, July 16, 2014

Display different boxplot groups on the same figure in MATLAB

a Simple example of how you could put the groups of boxplot together. Both of the data groups are in defined in one matrix .

 data = rand(20,24)  
 month = repmat({'jan' 'feb' 'mar' 'apr' 'may' 'jun' 'jul' 'aug' 'sep' 'oct' 'nov' 'dec'},1,2);  
 simobs = [repmat({'sim'},1,12),repmat({'obs'},1,12)];  
 boxplot(data,{month,simobs},'colors',repmat('rb',1,12),'factorgap',[5 2],'labelverbosity','minor');  



Here is the figure:

Tuesday, July 15, 2014

How to add an overall title to subplot in matlab

Here is the way to create a general title that span over all the subplots :

doc suptitle
try:
Suptitle('this is the super title')

Removing scientific notation in the tick label of a Matlab plot


here is the way you could manually set the tick labels yourself using sprintf:

yt = get(gca,'YTick');
set(gca,'YTickLabel', sprintf('%.4f|',yt))

Sunday, June 22, 2014

Mean Square Error Implementation and gfit2 function in matlab

most likely when you create a regression model you want to evaluate the model to estimate the googdness of your fit. Most common way of doing that is to calculate the mean square error. here is the implementation of that in Matlab :

 X = randn(256,256);  
   Xapp = randn(256,256);  
   D = abs(X-Xapp).^2;  
   MSE = sum(D(:))/numel(X);  

There is also a function by Richard Crozier that offer various methods to evaluate the goodness of fit. you can find it in here:






Thursday, May 15, 2014

3D Curve Fitting in Matlab(Linear and Higher Order Polynomial)

To fit a curve onto a set of points, we can use ordinary least-squares regression. There is a solution pageby MathWorks describing the process.
As an example, let's start with some random data:
% some 3d points
data = mvnrnd([0 0 0], [1 -0.5 0.8; -0.5 1.1 0; 0.8 0 1], 50);
As @BasSwinckels showed, by constructing the desired design matrix, you can use mldivide or pinvto solve the overdetermined system expressed as Ax=b:
% best-fit plane
C = [data(:,1) data(:,2) ones(size(data,1),1)] \ data(:,3);    % coefficients

% evaluate it on a regular grid covering the domain of the data
[xx,yy] = meshgrid(-3:.5:3, -3:.5:3);
zz = C(1)*xx + C(2)*yy + C(3);

% or expressed using matrix/vector product
%zz = reshape([xx(:) yy(:) ones(numel(xx),1)] * C, size(xx));
Next we visualize the result:
% plot points and surface
figure('Renderer','opengl')
line(data(:,1), data(:,2), data(:,3), 'LineStyle','none', ...
    'Marker','.', 'MarkerSize',25, 'Color','r')
surface(xx, yy, zz, ...
    'FaceColor','interp', 'EdgeColor','b', 'FaceAlpha',0.2)
grid on; axis tight equal;
view(9,9);
xlabel x; ylabel y; zlabel z;
colormap(cool(64))
1st_order_polynomial
---------------------------------------------------------------------------------
Higher-order Polynomial Fitting:
As was mentioned, we can get higher-order polynomial fitting by adding more terms to the independent variables matrix (the A in Ax=b).
Say we want to fit a quadratic model with constant, linear, interaction, and squared terms (1, x, y, xy, x^2, y^2). We can do this manually:
% best-fit quadratic curve
C = [ones(50,1) data(:,1:2) prod(data(:,1:2),2) data(:,1:2).^2] \ data(:,3);
zz = [ones(numel(xx),1) xx(:) yy(:) xx(:).*yy(:) xx(:).^2 yy(:).^2] * C;
zz = reshape(zz, size(xx));
There is also a helper function x2fx in the Statistics Toolbox that helps in building the design matrix for a couple of model orders:
C = x2fx(data(:,1:2), 'quadratic') \ data(:,3);
zz = x2fx([xx(:) yy(:)], 'quadratic') * C;
zz = reshape(zz, size(xx));
Finally there is an excellent function polyfitn on the File Exchange by John D'Errico that allows you to specify all kinds of polynomial orders and terms involved:
model = polyfitn(data(:,1:2), data(:,3), 2);
zz = polyvaln(model, [xx(:) yy(:)]);
zz = reshape(zz, size(xx));

2nd_order_polynomial

Sunday, April 20, 2014

Chang The Fonts For All The Text in Matlab Plots

If you want to change font size for all the text in a figure, you can use findall to find all text handles, after which it's easy to change:


figureHandle = gcf;
%# make all text in the figure to size 14 and bold
set(findall(figureHandle,'type','text'),'fontSize',14,'fontWeight','bold')

Wednesday, March 12, 2014

fitting 3d data

Imagine you have 2 variables and you want to create a regression model to predict the 3rd variables. for that you have two options:
1) use the surface fitting toolbox in matlab. enter the following command in the consol:
sftool
once it is launched, you would be able to provide your first and second variables as the factos for ceating the model and the 3rd variable as the predictor. You have also some options to fit different degree of polynomial and see how you model would be.


2) use the command line function to create the above model:
following command create a 3rd order polynomial fitting model using the data y1 and y2:
sf = fit([y1,y2],y3,'poly33')
this will plot your model and your training data:
plot(sf, [y1,y2], y3)

if you want to exclude a range of data at the time of creating model do this:
sf = fit([y1,y2],y3,'poly33','Exclude', y2 < 5)