Tag Archives: matlab

[matlab] modifying/manipulating shapefile (.shp) contents

Before you start reading:

  1. You should check if “Mapping Toolbox” is installed in your MATLAB first. You can check it by typing “ver” command on your MATLAB “Command Window”.
  2. I’m using MATLAB r2014a to test the code
  3. I’m using this SHP file: Shapefile for Polewali Mandar

Adding new field/attribute to the shapefile
Actually, until now, I don’t know how to do it using MATLAB alone. As you know, a shapefile (.shp) doesn’t stand alone, there always be some other files with the same name but different extension. The one we need if we want to add a new attribute/field into the shapefile is the file with .DBF extension. Yup, it’s just DBASEIII+ file. Usually I use LibreOffice Calc to open the .DBF file and then adding the new field as new column and save it back as .DBF file. See screenshot:

Adding new attribute/field via LibreOffice Calc

Adding new attribute/field via LibreOffice Calc

As you can see, I add new attribute, i.e. ‘KELAS’ which is character type field (‘C’) and has 11 in length.
You can always use specialized GIS apps to do this (such as QGIS) but I don’t have it on my working PC, so I just grab whatever I have. ūüėÄ

Opening a shapefile
as simple as this:

s=shaperead('polman'); % this will open POLMAN.shp and assign it to 's' variable

Deleting/removing attribute from shapefile
Use these code sequences:

spec=rmfield(spec, 'KELAS'); % let's delete KELAS attribute
shapewrite(s, 'new_polman', 'DbfSpec', spec); % save it to new shapefile (new_polman.shp) incase you want to keep the original

Finding object inside shapefile based on it’s attribute value
something like these:

dx=find(cellfun(@(x)strcmpi(x,'ALU'),{s.KECAMATAN})); % find all objects that 'KECAMATAN' attribute value is 'ALU'
% now, 'dx' will contain all object indexes that match the search criterion

Edit and save back the attribute value
An example:

s(33).KELAS='SANGAT LUAS'; % change the 'KELAS' attribute value of object number 33
shapewrite(s, 'polman'); % save the changes!

Viewing the shapefile interactively
Use the built-in interactive viewer:


It will open a new MapView window where you can import the shapefile from workspace variable or via opening the file directly.

MAPLAB's mapview

MAPLAB’s mapview

Matlab: Setting an image as form background

Image as form background in Matlab

Well, this is something new for me — new easy techniques — so I should post it here incase I forgot where to look.

Got the tips from here: http://stackoverflow.com/questions/13101661/how-to-put-a-background-image-in-a-figure-using-matlab-guide

So, supposed hat you want to make an image as the background image that span all over the form/figure. The first step is to edit the .m file that correspondent to your form/figure .fig.

Find your figure Opening function, it should look like this:

function halaman_utama_OpeningFcn(hObject, eventdata, handles, varargin)

Now, exactly before guidata(hObject, handles); code, you put these codes:

% create an axes that spans the whole gui
ah = axes('unit', 'normalized', 'position', [0 0 1 1]);
% import the background image and show it on the axes
bg = imread('the_background.jpg'); imagesc(bg);
% prevent plotting over the background and turn the axis off
% making sure the background is behind all the other uicontrols
uistack(ah, 'bottom');

Those codes will show “the_background.jpg” located in the same directory as your GUI files as your form background and stay below other UI controls.

[matlab] getting and setting value in other form/figure/gui

I often using need to do this in other visual programming (e.g. Visual Basic, Delphi), i.e. getting and setting value from other forms. Learning¬† Matlab gui programming, I was a bit puzzled on how to do this because obviously we can’t do this: form2.edit1 in our Matlab’s m-script. After some searching, I finally got it, so, here I share what I found to Matlab’s newbie like me.
To follow, we will create two figures via GUIDE named form_1.fig and form_2.fig. Here’s the design for form_1
form_1 design
There are two edit-text named edtValForm2 and edtNewValue. Two pushbutton named pbGetVal and pbSetVal.
This is the design of form_2
form_2 design
There’s only one edit text here, named edit1 and set the ‘String‘ property value to “This is the default value in Form #2“. No coding needed in this form_2 because we will change the edit text via form_1

Getting value from other form

You should run form_2 first.
View pbGetVal callback on your m-script editor and enter the code below:

% find form #2 (form_2) handle. Use findobj! We need to find a figure/form that has Name: form_2
hf2=findobj(0, 'Type', 'figure', 'Name', 'form_2');
% check if hf2 is true handle
if (ishandle(hf2))
    % hf2 is real handle, form_2 is already opened
    % now get a handle of edit1 in form #2
    edt1_Form2=findobj(hf2, 'Tag', 'edit1');
    % get the String value from edit1 in Form #2
    val_Form2=get(edt1_Form2, 'String');
    % show the value in our form (form_1)
    set(handles.edtValForm2, 'String', val_Form2);
    % hf2 is not a handle, means: the form_2 has not been opened yet
    warndlg('Form #2 not found! Maybe it''s not opened yet?');

The comments on the code should enough to explain what happened in the code

Setting value into other form

View pbSetVal callback and enter the code below:

% find form #2 (form_2) handle
hf2=findobj(0, 'Type', 'figure', 'Name', 'form_2');
% check if hf2 is true handle
if (ishandle(hf2))
    % hf2 is real handle, form_2 is already opened
    % now get a handle of edit1 in form #2
    edt1_Form2=findobj(hf2, 'Tag', 'edit1');
    % get the String value from our form
    val_Form1=get(handles.edtNewValue, 'String');
    % set the new value into Form #2 (form_2)
    set(edt1_Form2, 'String', val_Form1);
    % hf2 is not a handle, means: the form_2 has not been opened yet
    warndlg('Form #2 not found! Maybe it''s not opened yet?');

The codes also had comments to explain what happened.
Now run form_1, try clicking on pbGetVal and pbSetVal, you’ll see the effect.
form_1 and fomr_2 running together

Although I gave an example on edit text, this technique also work if you want to change other gui component value such as uitable ‘Data’ property or even plotting into axes in other form.

Matlab variable sharing (global variable and such and such…)

Coming from another programming language (Delphi/C#), the one puzzled me about programming in Matlab is how do I share my variable just like I programmed desktop application using Delphi or C#.

After reading the documentation and a lot of forum browsing, finally I made up my mind and conclude my own “best-practice” when I want to share (global) variables in Matlab. (This is applied when we are developing a Matlab GUI via GUIDE).

Sharing variables between functions in one Form/GUI

  • use guidata and handles.

create a global variable that will be known by all functions inside a form/GUI

handles.my_global_var=[1 3 4 2 7]; % just a dummy matrix
guidata(hObject, handles);

recall/access that global variable within other function (still in the same form)


caveat: all global variables is destroyed when you close the Form/GUI


Sharing variables between multiple Forms/GUI but in one application

  • use setappdata and getappdata

create a global variable

setappdata(0, 'my_global_var', the_value);

accessing it

local_var=getappdata(0, 'my_global_var');

checking it (if it’s already set or not)

if (isappdata(0, 'my_global_var'))
    % my_global_var is already set, do something
    % my_global_var isn't there, warn user

deleting it

rmappdata(0, 'my_global_var');

caveat: variables is gone when you close Matlab; you can’t see the variables within Matlab Workspace


The highest level: sharing between multiple Forms/GUI and also with your Matlab Workspace/Command Window

  • use assignin and evalin


assignin('base', 'variable_name', the_value);


local_var=evalin('base', 'variable_name');

See the variables in your Matlab Workspace so you can analyze the variable further (maybe via Variable editor or directly via Command Window)

matlab workspace window

Matlab workspace window showing global variable

caveat: variables is gone when Matlab is closed

If you want to create variables that will not gone even after Matlab closed, you can use save and load command. Checkout Matlab Help page for further documentation about save and load.


Detecting installed webcam via command line/m script file

On my previous Matlab tips, I already show you how to create a GUI (GUIDE)¬† to capture webcam picture. I show you how to easily detect installed and supported video format using imaqtool command. This time I’ll show you how to detect installed webcam without calling imaqtool window. This would be useful if you want to automatically detect installed webcam without needing user interaction/input.

Your Matlab still need Image Acquisition Toolbox though and your webcam should be connected before you open Matlab.

  • First step is to detect installed webcam drivers on in your Matlab, because it could be different on different platform (Windows/Linux/Mac).

Variable adaptors now will contain installed drivers on your Matlab. Example output would be (InstalledAdaptors is a cell):

>> adaptors.InstalledAdaptors

ans = 

    'matrox'    'winvideo'
  • Now we know that my Matlab knows ‘matrox’ and ‘winvideo’ driver. Our next step would be detecting is there any webcam attached to those drivers. Use this command :
  • For detecting how many installed webcam that detected as ‘matrox’ we can use:
>> numel(matrox_webcam.DeviceIDs)

ans =

  • Oh, as you can see, there’s no webcam detected as ‘matrox’ so we are certainly will not use this driver. How about ‘winvideo’ webcam, let’s check:
>> numel(winvideo_webcam.DeviceIDs)

ans =

  • Yup, there’s one installed and active there, let’s check further to know how to command Matlab to use this webcam:
>> winvideo_webcam.DeviceInfo(1).ObjectConstructor

ans =

videoinput('winvideo', 1)
  • Now you got what command that you should use to activate the webcam [videoinput(‘winvideo’, 1)]. How about the supported image/video formats supported by this webcam? Use this command:
>> winvideo_webcam.DeviceInfo(1).SupportedFormats

ans = 

  Columns 1 through 4

    'YUY2_160x120'    'YUY2_176x144'    'YUY2_320x240'    'YUY2_352x288'

  Column 5


Oh, there are 5 types of supported image/video. You can choose one.

Your information is now complete, you know which webcam is active, what command that need to be called to activate the webcam and which format available for this webcam. You can begin to capture the image/video from webcam using Matlab.

matlab 2011a logo

Tested on Matlab 2011a on Windows 7 64 bit within Asus Notebook A43SV