Search this blog!

Thursday, December 15, 2011

How to use binary variable/ TRUE FALSE in MATLAB?

You know in C++ you may write the following

bool binary_variable=TRUE; // Or FALSE

But How to do that in MATLAB?

>>true([m, n])
This will create an m-by-n matrix of binary (logical) ones // TRUE
>>false ([m, n])
For m-by-n matrix of binary (logical) zeros // FALSE

Wednesday, December 14, 2011

In MATLAB: find two tailed P value of t-distribution (Student's t-distribution)

Problem:
-----------
Given the t-ratio and the degrees of freedom(dof), find two tailed P value of t-distribution (Student's t-distribution)

Solution:
---------
Using the econometrics toolbox here is an example where t ratio = 2.2000 and degree of freedom= 5 ; The computed two tailed P Value is 0.0791



tdis_prb
function y = tdis_prb(x,n)
% PURPOSE: calculates t-probabilities for elements in x-vector
%---------------------------------------------------
% USAGE: y = tdis_prb(x,n)
% where: x = vector containing computed t-values
%        n = degrees of freedom parameter
%---------------------------------------------------
% RETURNS:
%        y = a vector of marginal probability levels
% --------------------------------------------------
% SEE ALSO: fdis_prb(), chis_prb
%---------------------------------------------------

% written by:
% James P. LeSage, Dept of Economics
% University of Toledo
% 2801 W. Bancroft St,
% Toledo, OH 43606
% jpl@jpl.econ.utoledo.edu


if nargin ~= 2; error('Wrong # of arguments to tdis_prb'); end;
if n <=0; error('dof is negative or zero in tdis_prb'); end;

x2 = n./(n+x.^2);
one = find(x2 >= 1);
if length(one) > 0
    x2(one,1) = 1-1e-12;
end;
zip = find(x2 <= 0);
if length(zip) > 0
    x2(zip,1) = 1e-12;
end;

tmp = 1.0 - 0.5*betainc(x2,0.5*n,0.5);
y = 2*(1-tmp);
x
n
end
x =

    2.2000


n =

     5


ans =

    0.0791

Exercise:
-----------
Using this function (tdis_prb) plot results for [-4:0.05:4] for 10 degrees of freedom. 

Tuesday, December 13, 2011

In MATLAB: Sort an Array and then Undo that sort

PROBLEM:
--------------
Imagine I have an array to be sorted and after I sort it I want to UNDO that sort so that the array came back to the initial condition.

How?
---------
 A=[10 9 7 4 5 7 5 3 ];
>> [SORTED_A,IX]=sort(A)

SORTED_A =
     3     4     5     5     7     7     9    10
IX =
     8     4     5     7     3     6     2     1

>> UNSORTED=1:length(A)
UNSORTED =
     1     2     3     4     5     6     7     8

>> NEW_INDEX(IX)=UNSORTED
NEW_INDEX =
     8     7     5     2     3     6     4     1


>> NEW_A=SORTED_A(NEW_INDEX)
NEW_A =
    10     9     7     4     5     7     5     3

>> isequal(A,NEW_A)

ans =

     1