From MATLAB To Python

Posted on


For many years MATLAB has been my primary tool for prototyping algorithms, because of its rich set of optimization functions and the AI tool box it has proven to be a valuable tool to have. However, It is not cheap and if you do not have a company to pay for license or attend a university that provides you with a license then you will have to find an alternative.

MATLAB is not a programming language rather its a tool that has as part of its framework a programming language called M language, this language has a lot of quirks and takes some getting use to, the other issue I found with MATLAB is that the functions while well documented do not seem to follow a standard in terms of parameters; on the whole while MATLAB is a good tool for prototyping and is used a lot in engineering and medical fields which are my core domain; However,I am forced to look for a cheaper/free alternative that will give me as much if not more tools than MATLAB now provides.

Python to the rescue:

Python is powerful… and fast;
plays well with others;
runs everywhere;
is friendly & easy to learn;
is Open

All these wonderful things make Python a big contender for my MATLAB replacement.

The first thing we want to do is install Python.
Next install my favurite Python IDE PyCharm
Create a new Python Project using PyCharm
Python project

How do we add packages to our project?
Python is nothing without its packages and two of my favourites are numpy and scipy. To add these packages simply download the Anaconda distribution and configure it to be your default python implementation.


And here is my first piece of python code as taken from the python website 🙂


All I need now is a good Python book and 2-4 months to delve into the language. Stay tuned for more posts on my Python journey. Happy coding!!


Posted on Updated on

This little code snippet converts MATLAB Struct to xml, enjoy!!

Mapping A Maze Using MATLAB Image Processing Toolbox

Posted on Updated on

Recently I saw an article about mapping a maze and I thought to myself; how could this be achieved using my favorite tool MATLAB :-)? Well it turns out that its a pretty simple task. Some functions used in this post require that you have MATLAB 2012a or higher installed, so if u do not then go away and get it.

Wow you are back, ok so lets begin, first we will look at the code that was used and then further down we will look at individual functions and what they were used to do.

The maze:

The code:

%% Map Maze
im = imread('maze.png');
bw = im2bw(im(1:287, 1:400), 0.45);
cc = bwconncomp(bw, 8);
obj = false(size(bw));
obj(cc.PixelIdxList{13}) = true;
sln = bwmorph(bwmorph(obj,'thin',Inf),'spur', Inf);
figure, imshow(imfuse(im,sln,'blend','Scaling','joint'))

clear Clears all variables from the MATLAB workspace.
im = imread(‘maze.png’);
Reads the maze image and stores it.
bw = im2bw(im(1:287, 1:400), 0.45); Converts the image to binary, scales it and stores it.
cc = bwconncomp(bw, 8); Find connecting components within the image.
obj(cc.PixelIdxList{13}) = true; Find the largest component and select it.
sln = bwmorph(bwmorph(obj,’thin’,Inf),’spur’,Inf); Use Morphological functions to refine image.
figure, imshow(imfuse(im,sln,’blend’,’Scaling’,’joint’)); Overlay and display images


solved maze

The end 🙂

Wheatstone Bridge In MATLAB Simulink

Posted on Updated on

The diagram below describes a Wheatstone bridge designed with MATLAB Simulink, The resistor designated [R x] can be replaced with a variable resistance material and used in the construction of a strain gauge.

Wheatstone bridge is an electrical circuit used to measure an unknown electrical resistance by balancing two legs of a bridge circuit, one leg of which includes the unknown component. Its operation is similar to the original potentiometer. It was invented by Samuel Hunter Christie in 1833 and improved and popularized by Sir Charles Wheatstone in 1843. One of the Wheatstone bridge’s initial uses was for the purpose of soils analysis and comparison read more

Simulink Circuit Schematic:
wheatstone bridge

DC Voltage = 100 v
R 1 = 10 ohm, R 2 = 10 ohm, R 3 = 10 ohm, R x = 5 ohm
Connect the components as seen in the diagram then run the simulation, let [R x] be the variable resistance material; vary the resistance to see the difference in current.

NB: Resistors were taken from the  powerlib Simulink components [Parallel RLC Branch]

Solving Crossword Puzzles Using Image Acquisition And Data Scraping (Part 2)

Posted on Updated on

In this the second part of the crossword puzzle solver series, we will look at writing to the video input stream. The image acquisition toolbox allows the programmer to configure a function called the UpdatePreviewWindowFcn . Once configured, we can use this function along with others from the vision toolbox like vision.TextInserter and vision.ShapeInserter to add artifacts to the video stream before calling the preview function.

Lets see some code:

vid = videoinput('winvideo', 1, 'YUY2_1280x720');
src = getselectedsource(vid);

vid.FramesPerTrigger = 1;
vid.ReturnedColorspace = 'rgb';

vidRes   = get(vid, 'VideoResolution');
imWidth  = vidRes(1);
imHeight = vidRes(2);
nBands   = get(vid, 'NumberOfBands');
hImage   = image(zeros(imHeight, imWidth, nBands));

setappdata(hImage,'UpdatePreviewWindowFcn',@mypreview_fcn); % configure update udf.

preview(vid, hImage) % display updated stream.

Update Preview UDF code:

function mypreview_fcn(obj,event,himage)
    % display image data.
    tx = vision.TextInserter('Hello World!');
    tx.FontSize = 40;

    set(himage, 'cdata', step(tx, event.Data))

Result: See Hello World! printed in the top left hand corner of the stream.

This functionality will be very important when we get to actually superimposing the solution to the crossword puzzle on the video output stream.

Solving Crossword Puzzles Using Image Acquisition And Data Scraping (Part 1)

Posted on

Crossword puzzles are a very popular pastime in most parts of the western world, and provide a quick means of escape for those on the commute or on break from regular work. The solution to the more interesting puzzles require a fairly good vocabulary and the ability to spot patterns and word arrangements. I recently saw an article on using MATLAB to solve a Sudoku puzzle using image acquisition toolbox and a Sudoku solver algorithm. This series of articles will take a slightly different approach, we will still use the image acquisition toolbox; however, instead of an algorithm to solve the puzzle we will use data scraping form a puzzle website to get the most suitable word for a particular place in the crossword.

The website we will be using to get solutions is  One Across

MATLAB is built on the java platform and is able to execute java code written at the command line or inserted in .m files. This feature will be exploited in future articles for doing tasks more suitable to the java toolset.

Example Java and MATLAB code in one .m file


data = URLEncoder.encode('');
url  = URL('');
con  = url.openConnection(); con.setDoOutput(true);
wr   = OutputStreamWriter(con.getOutputStream());

rd   = BufferedReader(InputStreamReader(con.getInputStream()));

while rd.readLine() ~= '' %MATLAB CODE
    line = ans;

In part two of this series we will look at using image acquisition to capture a live video feed for the puzzle we want to solve and overlaying the possible solution unto the video feed, stay tuned.

Designing A Custom Neural Network In MATLAB

Posted on Updated on

The MATLAB Neural Network toolbox ships with numerous predefined and canonical neural nets, however sometimes you may need to create a custom net with just the right connections, biases and hidden layers to suite your particular problem domain. To achieve this goal we can use the matlab network object. The  network object allows granular design of neural networks by exposing all properties of the net that we are designing. The preceding code demonstrates how to build a simple neural to learn the truth table for Logical AND.

First lets look at the Logical AND truth table:

p q p ∧ q

Open a new edit window in MATLAB and enter the following code:

    1. This creates an empty network object and assigns it to the net variable, sets up the number of inputs and uses cell array syntax to index into its properties.
      %% Design Custom Neural Network
      net = network;                                  % create network
      net.numInputs = 2;                              % set number of inputs
      net.inputs{1}.size = 1;                         % assign 2 to input size
      net.inputs{2}.size = 1;
      net.numLayers = 1;                              % add 1 layer to network
      net.layers{1}.size = 1;                         % assign number of neurons in layer
      net.inputConnect(1) = 1;                        % connet input to layer 1
      net.inputConnect(2) = 1;
      net.biasConnect(1) = 1;                         % connect bias to layer 1
      net.biases{1}.learnFcn = 'learnp';              % set bias learning function
      net.biases{1}.initFcn = 'initzero';             % set bias init function
      net.outputConnect(1) = 1;
      net.layers{1}.transferFcn = 'hardlim';          % set layer transfer function [hard limit]
      net.inputWeights{1}.initFcn = 'initzero';       % set input wieghts init function
      net.inputWeights{1}.learnFcn = 'learnp';        % set input weight learning function
      net.inputWeights{2}.learnFcn = 'learnp';
      net.inputWeights{2}.initFcn = 'initzero';
      net.initFcn = 'initlay';                        % set network init function
      net.trainFcn = 'trainc';                        % set network training function
      net.performFcn = 'mae';                         % set network perf evaluation function
      net = train(net,[0 0 1 1;0 1 0 1],[0 0 0 1]) ;  % train network
    2. Custom Network Diagram:
    3. Test Network
      In the command window type


      This should output a 1 to the command window indicating 1 AND 1 = 1