python4enlightening

the open notebook

Matlab Code in iPython Notebook

I was very pleased today to find out that some people made a library which makes it possible to utilize MATLAB code directly in the iPython Notebook, which this webpage is written in. As you see in the In[134] the library is called pymatbridge. For me personally this is advantageous because most of the material at this semester is based on utilizing MATLAB libraries, so now this webpage is directly compatible with my daily work, with \(\LaTeX\), MATLAB and Python.

Importing pymatbridge and starting MATLAB

This is how to enable the bridge.

In [2]:
import pymatbridge as mpb
ip = get_ipython()
mpb.load_ipython_extension(ip)

Example of plotting

In [3]:
%%matlab
a= linspace(0,6*pi,1000);
plot(sin(a)+0.25*sin(20*a+0.5*pi))
title('Test Plot of Amplitude Modulation Signal','fontsize',18)
xlabel('n','fontsize',16)
ylabel('f(n)','fontsize',16)

Matrix Syntax and Covariance Matrices

Covariance Matrix

Now we will show how to calculate the covariance matrix by matrix multiplications.

In [4]:
%%matlab
format compact
    X =  [1+j 2-j;3+j 4-j]
    [m,n] = size(X);
    ONE = ones(1,m)
    
    X_bar = mean(X)
    X_bar = (X_bar'*ONE)'
    
    R = X-X_bar
    
    Covariance = (R'*R)/(m-1)
X =
   1.0000 + 1.0000i   2.0000 - 1.0000i
   3.0000 + 1.0000i   4.0000 - 1.0000i
ONE =
     1     1
X_bar =
   2.0000 + 1.0000i   3.0000 - 1.0000i
X_bar =
   2.0000 + 1.0000i   3.0000 - 1.0000i
   2.0000 + 1.0000i   3.0000 - 1.0000i
R =
    -1    -1
     1     1
Covariance =
     2     2
     2     2

And basically, the correlation matrix is a scaled version of the covariance matrix. It is scaled to the sample variance as follows: Firstly, we define the covariance as \(\sigma\) and the correlation \(C\)

Correlation Between Two Vectors

Now we will do a quick example of plotting the correlation between 2 measurements of 400 random samples. Therefore, they do show no correlation.

In [5]:
%%matlab
    X=rand(400,2);
    x_bar = mean(X)'

    x_covar = cov(X)
    
    x_corr = corr(X)

    R = corrcoef(X)

    Sn = x_covar; fprintf('\n------------------------------------------------\n'); 

    figure
    a=1;b=2;
    scatterhist(X(:,a),X(:,b),100);
    xlabel(sprintf('Column %1.0f',a),'Fontsize',15); ylabel(sprintf('Column %1.0f',b),'fontsize',15);
x_bar =
    0.4997
    0.4969
x_covar =
    0.0783    0.0007
    0.0007    0.0801
x_corr =
    1.0000    0.0088
    0.0088    1.0000
R =
    1.0000    0.0088
    0.0088    1.0000

------------------------------------------------

Comments