Skip to main content

Tools for Scientific Computing - MATLAB and Python

Tools for Scientific Computing - MATLAB and Python

What You will Learn

  • You will learn the needs for and the requirements in scientific computing.
  • You will learn the basics of MATLAB and Python and make a comparative study.
  • You will learn to use freemat to interpret MATLAB codes.
  • You will do some basic coding in MATLAB and Python.

Overview

Computers are incredibly powerful systems that facilitate the many walks of human life. In working with computers, it is imperative to know how to talk them into doing useful things. There is a plethora of programming languages such as C, C++, PHP etc. that serve this purpose. But when it comes to prompting a computer to do scientific computing tasks, there are very few languages with desirable features such as FORTRAN , Ruby, Python etc. This post presents the scientific computing requirements the desirable features of programming languages indented for scientific purposes. The rest of the chapter deals with Python, an object-oriented and modular language, with stress on its signal processing tool boxes and the plotting libraries.

Scientific Computing - Needs and Issues

The features that earmark a language for scientific computing are
  • There should be an interactive terminal that can interpret the code line by line. A compiled language is not a right candidate.
  • Easy and fast vector, matrix and array operations including multiplication with minimum coding hassles.
  • A publication quality plotting library with post script output preferrably with $\LaTeX $ fonts for axes and text.
  • This post will introduce two languages viz. MATLAB and Python for scientific computing.

    MATLAB

    It is a commercial software for scientific computing. While it is very popular in academia and industry, its cost makes it not affordable for most people. MATLAB can be purchased from and be installed following the steps in the manual. If you cannot afford the purchase, you may use freemat for running the MATLAB code.

    Installation of freemat

    Freemat is installed on Windows by downloading the .exe from . If you have trouble, give a google search on freemat download.
    Freemat is installed on Linux using either
    $\fbox{sudo apt-get install freemat}$
    or
    $\fbox{yum install freemat }$
    commands from a terminal, depending on whether it is a apt-based Linux (such as Ubuntu) or a yum based system (such as Fedora, Red Hat)

    Simple Examples in MATLAB

    MATLAB is an interpreter based meta-language whose operations in MATLAB rely on matrix operations.The code can be written and interpreted from the MALAB/freemat command line. If the code is long, they can be entered into the editor and saved as a .m file. This file can be interpreted by MALAB/freemat.

    A simple array $x$ is declared as
    x=1:10:0.1;
    If the semicolon is missing, the command line echoes the array that starts with $1$ and ends with $10$ with increment $0.1$. The length of this array is ascertained with the length() command as
    length(x)
    returns $100$.

    Point by Point Array Multiplication

    Such a multiplication is useful in filtering applications. Let us defines two identical sized arrays $x$ and $y$ and multiply them point by point using $.*$ operation as
    x=[1,2,3];
    y=[4,5,6];
    z=x.*y
    returns the array [4,10,18]

    Matrix Multiplication

    Well, this is MATLAB is all about! Consider a $3\times 2$ matrix $x$ and a $2\times4$ matrix $y$. The product $x\times y$ is computed with the following code.
    x=[3,2;4,5;6,7];
    y=[1,2,3,4;4,5,6,7];
    x*y returns the $3\times 4$ matrix product.

    Complex Numbers

    Type sqrt(-1) at the interpreter. It returns $0+1i$. Also the complex function is used to generate complex numbers. For example, complex(3,2) returns $3+2i$. Complex vectors are generated as x=[1,2,3] y=[4,5,6] Try complex(x,y) and observe the output.

    Plot of Sinus Function

    The sinus function $y=\sin{x}$ is simulated and plotted by the following MATLAB code
    x=linspace(0,10,1000);
    y=sin(x);
    plot(x,y,'r');
    grid;
    The first line defines a vector $x$ with starting value $0$ and ending value $1$, with $1000$ linearly spaced values. i.e. with the increment $0.01$. The second line computes the sine function $y=\sin{x}$. The third line plots the sine function in red color, as dictated by the string 'r'. The $grid$ inserts a grid in the GUI. The GUI can be saved as a jpeg file in MATLAB and in a large number formats (including .eps and .png) in the case of freemat. See the picture below. You may try to plot various other functions in this manner.

    Python

    While MATLAB is a costly software that is meant for use in isolated machines, there is a need for a full fledge language for scientific computation. This language should support object oriented features and distributed computing should be free in every sense. After all, poor people also need to compute ! Right? Such a language is Python, whose name is derived from the show Monty Python and not from snakes. You may visit for details on Python. While there is $2.x$ and $3.x$ version, it is better to stick to the $2.x$ version. The current version is $2.7$, on which the codes in this post are based on. You may visit my blog for a basic introduction to Python and its use in signal and image processing.

    Comparison between MATLAB and Python

    MATLAB Python
    Proprietary and expensive. Can be freely downloaded and installed
    The user has no right to modify the software. The user can tailor the code according to need
    Distribution of code execution not possible Distributed computing is possible
    Meta language Full fledged object oriented language
    Large volume of pre-written code The volume of codes generated is not as big as MATLAB
    Slow Almost as fast as C
    Relies on matrix operations Relies on array operations
    All tool boxes and utilities become active on initialization of MATLAB and the execution is burdensome. Modular language, so light and robust.
    Does not support zero indexing Supports zero indexing

    Now let consider how Python is used in realizing the above tasks. Much of the scientific computing is done with the help of the module $scipy$. High quality plots are generated by the Python library $MATPLOTLIB$ alias $pylab$.

    Installation Python and Important Modules

    You may download the anaconda distribution of Python from and install in Windows. Stick to the $2.7$ version. In Linux, the installation is done by the root user with the commands
    sudo apt-get install python-scipy
    sudo apt-get install python-matplotlib
    sudo apt-get install ipython
    The last line installs the enhanced interactive shell, called IPython, which acts very much like MATLAB command line.

    Arrays in scipy

    Launch ipython and type from scipy import *
    x=r_[1:10:0.01]
    at the interpreter. The first line imports all modules under scipy. The second line creates a scipy array with starting value $1$ and the last value $9.99$ with increment $0.01$. Note that $10$ is not included. Type $x$ and observe the array. You may verify the length of the array with
    len(x)
    should return $900$.
    Elements in the array are accessed by say
    print x[10]
    returns $1.1000000000000001$.

    Point by Point Array Multiplication

    Type the code at the Ipython shell as
    . from scipy import * x=r_[0:5]
    y=r_[5:10]
    x*y returns $array([ 0, 6, 14, 24, 36])$

    Matrix Multiplication

    from scipy import * x=mat([[3,2],[4,5],[6,7]])
    y=mat([[1,2,3,4],[4,5,6,7]])
    x*y returns the $3\times 4$ matrix product.

    Complex Numbers

    Type sqrt(-1) at the interpreter. It returns $0+1*j$. Also the complex function is used to generate complex numbers. For example, complex(3,2) returns $3+2*j$. Complex vectors are generated as
    x=r_[6:9]
    y=r_[3:6]
    Try x+1j*y and observe the output.

    Plot of Sinus Function

    The sinus function $y=\sin{x}$ is simulated and plotted by the following Python code
    from scipy import *
    from pylab import plot, grid, show
    x=linspace(0,10,1000)
    y=sin(x);
    plot(x,y,'r');
    grid('on);
    savefig('sinusplot.eps')
    show()
    The savefig command saves the GUI in .eps format in the current working directory.See the picture below. You may try to plot various other functions in this manner.

    What You Learned

  • You understood the need for scientific computing .
  • You learned basic coding in MATLAB and Python.
  • Comments

    Popular posts from this blog

    RC Integrator and Differentiator using QUCS

    RC Integrator and Differentiator using QUCS Dr. Hari V S Department of Electronics and Communication College of Engineering Karunagappally What You will Learn You will understand the operation of simple integrator and differentiator circuits using QUCS You will learn the frequency response characteristics of integrator and differentiator by dint of ac simulation. Theory Differentiator is a high pass circuit that produces the time derivative of the input signal at the output. The circuit is shown below. \begin{equation} \nonumber v_{o}=I_{o}R=RC\frac{d(v_{s}-v_{o})}{dt}\\

    Generation of Signals using MATLAB/Python

    Generation of Signals using MATLAB/Python Dr. Hari V S Department of Electronics and Communication College of Engineering Karunagappally What You will Learn You will learn about various energy signals and their generation using MATLAB and python. Signal Generation using MATLAB MATLAB arrays are used to generate finite energy signals. It should be understood that the signals so generated are discrete in time and amplitude. Sinusoidal Signal Consider the sinusoidal signal $x=sin(t)$, which is nothing but a single tone, with the help of the MATLAB code below. t=linspace(0,10,5000); x=sin(t); plot(t,x); grid; The execution of the code will result in the signal, shown below. Amplitude Modulated Signal The above low frequency tone is used to modulate a sinusoidal carrier $y$ of ten times the original frequency. i.e. $y=sin(10t)$. The amplitude modulated signal $am(t)$ is obtained as \begin{equation} am(t)=x*y+y \end{equation}Su

    Voltage Divider Circuit using QUCS

    SPICE Simulation of Voltage Divider Dr. Hari V S Department of Electronics and Communication College of Engineering Karunagappally What You will Learn You will wire up a voltage divider network using QUCS You will learn to perform DC, AC and transient simulations on the developed circuit. you will learn to observe, store and export the data from the display ( .dpl ) file. Experiment Launch QUCS. Go to Components in the left pane and select the item Lumped Components . Drag and drop a resistor onto the schematic window. Right click on on to and go to Edit properties and make the resistance 1 k&#937 Right click, copy and paste this resistor twice. Connect the three resistors in series by wires, selected by pressing Cntrl+E . Go to Components in the left pane and select Sources &#8594 ac Voltage Source . Drag and drop the source onto the schematics window. Right click on the source and change