UNIT 5: ADVANCED MATLAB PROGRAMMING & APPLICATION DEVELOPMENT
5.1 Advanced Programming Constructs & Code Optimization
Goal: Write faster, memory-efficient MATLAB code.
| Technique | Description & Key Commands |
|---|---|
| Profiling | Identify slow code sections. <br> profile on → run code → profile viewer (or profile report). Shows function execution times and call counts. |
| Preallocation | CRITICAL: Allocate array size before loops. Avoids dynamic resizing (memory copy overhead). <br> A = zeros(N,1); or A = NaN(M,N); |
| Vectorization | Replace for loops with array/matrix operations. MATLAB is optimized for vector/matrix math. <br> Example: y = sin(x) vs. for i=1:length(x), y(i)=sin(x(i)); end |
| Memory Mgmt. | whos (display variable info), clear varName (remove variable), clear all (remove all). <br> pack (historical, defragments memory; rarely needed now). |
| Large Data Sets | Use memory-mapped files for data larger than RAM. <br> m = memmapfile('bigdata.dat', 'Format', {'double' [1000 1000] 'X'}); <br> Access parts via m.Data.X. |
| Efficient Loops | If vectorization impossible: <br> 1. Minimize operations inside loop. <br> 2. Precompute constants outside. <br> 3. Use logical indexing instead of if inside loops where possible. |
[!TIP] Common Pitfall: Growing an array inside a loop (
A = [A newElement]) is the #1 cause of slow MATLAB code. Always preallocate.
5.2 Graphical User Interface (GUI) Development
Goal: Build interactive applications with visual components.
| Aspect | App Designer (Modern) | Legacy GUIDE (Deprecated) |
|---|---|---|
| File Type | .mlapp (binary) |
.fig + .m |
| Layout | Grid Layout, Auto-Reflow (responsive). Drag-and-drop. | Manual positioning (pixels). |
| Code Structure | Auto-generated app class. Callbacks as methods. |
handles structure passed to callbacks. |
| Deployment | Directly compilable. | Requires conversion. |
Core UI Components (App Designer):
-
UIAxes(for plotting) -
Button,EditField(text/numeric),DropDown,Slider,CheckBox,ListBox
Callbacks & Data Sharing:
-
Callback function signature:
function ButtonPushed(app, event) -
Share data via
appproperties (define in Code View → Properties section). <br> Example:app.SharedData = [1 2 3]; -
Avoid
globalorhandlesin App Designer.
Deployment:
-
In App Designer: App Compiler tool.
-
Select "Standalone Application".
-
Specify main file (
*.mlapp). -
Runtime: Users need MATLAB Runtime (MCR) installed (free download).
5.3 Advanced Graphics & Visualization
Handle Graphics System:
MATLAB graphics are objects in a hierarchy:
Figure
└── Axes
├── Line (plot)
├── Scatter
├── Text
└── Image
-
Get handle:
h = plot(x,y);(h is aLineobject). -
Modify properties:
h.LineWidth = 2;orset(h, 'LineWidth', 2);
Advanced Plot Types:
-
Error bars:
errorbar(x, y, err) -
Stem:
stem(x,y) -
Scatter (varying):
scatter(x,y,sz,c)(sz=size vector, c=color vector/colormap) -
Filled contour:
contourf(X,Y,Z)
Subplots & Layouts:
-
Modern:
tiledlayout(m,n)+nexttile(better spacing/control thansubplot).tiledlayout(2,2); nexttile; plot(x1); nexttile; plot(x2); -
Legacy:
subplot(m,n,p)
Animations & Real-Time:
-
Inside loop:
drawnow limitrate(updates figure, limits rate to screen refresh) ordrawnow. -
pause(0.01)controls speed. -
For high-speed: Update
XData/YDataof existing plot object instead ofplotrepeatedly.
5.4 Object-Oriented Programming (OOP) in MATLAB
Defining a Class:
classdef MyClass
properties (Access = private)
PrivateData
end
properties (Constant)
PI = 3.14159;
end
properties (Dependent)
ComputedProp % No storage; get/set methods define behavior.
end
methods
function obj = MyClass(val) % Constructor
obj.PrivateData = val;
end
function val = get.ComputedProp(obj)
val = obj.PrivateData^2;
end
end
methods (Static)
function z = staticFunc(x)
z = x*2;
end
end
end
Key Attributes:
-
Properties:
SetAccess(public/private),GetAccess,Constant,Dependent. -
Methods:
Access(public/private),Static(no object needed),Hidden(not shown in docs). -
Handle vs. Value Classes:
-
Handle class: Inherit from
handle. Objects are references. Changes affect all copies. Used for GUI components, graphics objects.classdef MyHandleClass < handle -
Value class: Default. Objects are copies (like structs). Changes to copy don't affect original.
-
-
Inheritance:
classdef SubClass < SuperClass -
Packages: Folder name prefixed with
+(e.g.,+mypkg). Class inside:mypkg.MyClass.
Events & Listeners:
-
Define event in
eventsblock:events; MyEvent; end -
Trigger:
notify(obj, 'MyEvent') -
Listen:
addlistener(obj, 'MyEvent', @callbackFunction)
5.5 Interfacing with Other Languages & Systems
| Interface | Method & Example |
|---|---|
| Python | Call Python modules directly. <br> py.importlib.import_module('numpy') <br> np = py.importlib.import_module('numpy'); <br> arr = np.array([1,2,3]); <br> Convert types: double(arr) |
| Java | Use Java classes if on JVM. <br> list = java.util.ArrayList(); <br> list.add(10); |
| .NET | Requires Windows. Add assembly: NET.addAssembly('MyDll.dll'); <br> Use .NET objects. |
| MEX Files | C/C++/Fortran code compiled to MEX (.mexw64 etc.). <br> 1. Write C function mexFunction. <br> 2. Compile: mex myfunc.c. <br> 3. Call as myfunc() in MATLAB. Fastest integration. |
| Database | Database Toolbox: <br> conn = database('dbname','user','pass','org.sqlite.JDBCDriver','jdbc:sqlite:db.sqlite'); <br> data = fetch(conn, 'SELECT * FROM table'); |
| OS & Files | System command: [status, cmdout] = system('dir') (Windows) / 'ls' (Unix). <br> File I/O: fopen, fread, fwrite, fclose. <br> dir, copyfile, delete. |
5.6 Parallel and Distributed Computing
Parallel Computing Toolbox (PCT):
| Feature | Description & Syntax |
|---|---|
parfor |
Parallel for loop. Restrictions: <br> - Iterations must be independent (no i used in j's iteration). <br> - Variables classified: Loop, Sliced, Reduced, Broadcast. <br> - No break/return. <br> parfor i = 1:N, results(i) = heavyCalc(i); end |
spmd |
Single Program Multiple Data. Code runs on each worker. <br> spmd <br> A = rand(1000); % Each worker has own A <br> B = sum(A); <br> end <br> B{1} gets result from worker 1. Use labindex, numlabs. |
| Distributed Arrays | Data split across workers' memory. <br> D = distributed(rand(10000)); <br> Operations on D executed in parallel. |
| GPU Computing | gpuArray: Transfer data to GPU. <br> G = gpuArray(A); <br> B = sin(G); % Computed on GPU <br> B = gather(B); % Back to CPU. <br> arrayfun(@myfunc, G) for custom GPU functions. |
[!TIP]
parforvsfor: Useparforonly if loop iterations are heavy and independent; overhead of parallelization can make it slower for small tasks.
5.7 Advanced Toolbox Applications (Selective Overview)
| Toolbox | Key Functions & Use |
|---|---|
| Symbolic Math | syms x y, f = sin(x) + y^2; <br> diff(f,x), int(f,x), solve(f==0, x), vpa(expr) (variable-precision). |
| Optimization | Linear: linprog <br> Nonlinear: fmincon (constrained), fminunc (unconstrained), lsqnonlin (curve fitting). <br> Problem struct: options = optimoptions('fmincon','Display','iter'); |
| Curve Fitting | fit(x,y,fitType) (e.g., 'poly2', 'smoothingspline'). <br> spaps (smoothing spline). |
| Image Processing | imread, imshow, imfilter, edge (Canny), imbinarize, regionprops. |
| Signal Processing | fft, ifft, filter (IIR/FIR), designfilt (filter design), spectrogram. |
5.8 Testing, Debugging, and Documentation
Debugging:
-
Breakpoints: Click margin or
dbstop in file at line. -
Step:
dbstep,dbstep in,dbstep out. -
Continue:
dbcont, Quit:dbquit. -
dbstop if error(stops on error). -
dbstack(show call stack).
Unit Testing:
classdef MyTest < matlab.unittest.TestCase
methods (Test)
function testAddition(testCase)
act = add(1,2);
exp = 3;
testCase.verifyEqual(act, exp);
end
end
end
Run: runtests('MyTest').
Documentation:
-
publish('script.m', 'html')→ Generates HTML with code, output, figures. -
Options:
'pdf','latex'. -
Comments:
%%for sections.% TODO:recognized.
MATLAB Projects:
-
matlab.project.createProjector via Project tab. -
Manages files, dependencies, source control (Git/SVN), tasks, shortcuts.
-
Ensures reproducibility.
5.9 Deployment and Application Distribution
MATLAB Compiler (mcc):
-
Command:
mcc -m myapp.m(console app) or-W WinMain:myapp(Windows GUI). -
App Designer: Use App Compiler app → generates installer.
-
Output: Executable +
runtimefolder (or web app archive).
Web Apps:
-
Create App in App Designer.
-
App Compiler → Web App.
-
Deploy to MATLAB Web App Server (requires license).
-
Users access via browser.
Toolbox Packaging:
-
matlab.addons.toolbox.packageToolbox('mytoolbox.prj')→.mltbxfile. -
Shareable, installable via Add-Ons → Install from File.
Runtime Dependencies:
-
MATLAB Runtime (MCR) must be installed on target machine.
-
Version must match MATLAB version used for compilation.
-
Include any custom files (data, images) via Additional Files in compiler.
-
Toolboxes: If code uses toolboxes, target must have corresponding toolbox runtime (some toolboxes require separate runtime installers).