UNIT 4: Advanced MATLAB Programming & Application Development
1.0 Advanced Programming Constructs & Functions
1.1 Function Handles & Anonymous Functions
-
Function Handle: A variable that stores a reference to a function, created using the
@operator.fhandle = @sin; % Handle to built-in function result = fhandle(pi/4); -
Anonymous Function: A simple, one-line function defined without a separate
.mfile. Captures workspace variables at creation.sq = @(x) x.^2; % Anonymous function y = sq(5); % Returns 25 -
Passing Functions as Arguments: Essential for functions like
fminbnd,integral,fsolve.integral(@(x) exp(-x.^2), 0, 1);
[!TIP] Common Pitfall: Anonymous functions capture values, not variables. If a variable used in the anonymous function changes later, the function still uses the original captured value.
1.2 Advanced Function Definition & Scope
-
Nested Functions: Functions defined inside another function. They have access to the parent function's workspace.
function outer(x) y = x^2; function z = inner(a) z = y + a; % Can access 'y' from outer end end -
Subfunctions: Additional functions in the same
.mfile after the main function. Visible only to other functions in that file. -
Private Functions: Functions in a
privatesubfolder. Accessible only by functions in the parent folder. -
Variable Inputs/Outputs:
-
varargin: A cell array containing any number of input arguments. -
varargout: A cell array for any number of output arguments.
function varargout = myfunc(varargin) n = nargin; for i = 1:n varargout{i} = varargin{i} * 2; end end -
1.3 Persistent & Global State
-
Persistent Variables: Retain their value between function calls. Must be explicitly declared and initialized inside the function.
function count_calls() persistent call_count; if isempty(call_count) call_count = 0; end call_count = call_count + 1; fprintf('Called %d times\n', call_count); end\boxed{\text{Persistent variables are local to the function but retain state.}}
-
Global Variables: Shared across multiple functions and the base workspace. Declared with
globalkeyword in every function/workspace using it.global myGlobalVar; myGlobalVar = 10;[!TIP] Best Practice: Avoid global variables when possible. They make code harder to debug and test. Prefer passing arguments or using nested functions for shared state.
2.0 Graphical User Interface (GUI) Development
2.1 GUI Development Environments
| Feature | GUIDE (Legacy) | App Designer (Modern) |
|---|---|---|
| Paradigm | Procedural, callback-based | Object-Oriented (class-based) |
| File Types | .fig (layout) + .m (code) |
Single .mlapp file (code + layout) |
| UI Components | Legacy uicontrol |
Modern uifigure components (uibutton, uislider) |
| Layout | Absolute positioning | uigridlayout, uiflowcontainer |
| Future | Deprecated (no new features) | Recommended for new apps |
2.2 Core UI Components & Layout
-
Components:
uibutton,uislider,uidropdown,uilistbox,uieditfield,uiaxes. -
Layout Management:
-
uigridlayout: Grid-based, responsive layout (rows/columns). -
uiflowcontainer: Arranges components in a row or column. -
Absolute positioning: Setting
Positionproperty directly (less flexible).
-
2.3 Callback Programming & Event Handling
-
Callback Structure: A function executed in response to an event (e.g., button click). Receives
src(object handle) andevent(event data).function ButtonPushed(src, event) val = src.Value; % Access component property end -
Sharing Data Between Callbacks:
-
GUIDE:
guidata(hObject, handles)stores/retrieveshandlesstructure. -
App Designer: Store data in app properties (recommended) or use
setappdata/getappdata.
% In App Designer properties (Access = private) SharedData end -
[!TIP] Key Difference: In App Designer, the
appobject is automatically passed to all callbacks, providing direct access to app properties and UI components.
2.4 Creating Deployable Applications
-
MATLAB Compiler: Packages MATLAB code (including GUIs) into standalone applications or shared libraries.
-
MATLAB Runtime (MCR): Required library installed on target machines to run compiled apps.
-
Packaging: Use Application Compiler app (
deploytool) ormcccommand. -
Web Apps: App Designer can create web apps deployed to MATLAB Web App Server (requires license).
3.0 Object-Oriented Programming (OOP) in MATLAB
3.1 Class Definition & Structure
classdef MyClass
properties (Access = private)
PrivateProp
end
properties (Constant)
CONST_VAL = 42;
end
methods
function obj = MyClass(arg) % Constructor
obj.PrivateProp = arg;
end
function out = method1(obj)
out = obj.PrivateProp * 2;
end
end
end
-
Properties Block: Define class data. Attributes:
Access(public/private/protected),Constant,Dependent(computed on get/set),Hidden. -
Methods Block: Define class functions. Can specify
(Access = private)for individual methods.
3.2 Constructors, Destructors & Lifecycle
-
Constructor: Method with same name as class (
obj = MyClass(args)). Initializes object properties. -
Destructor:
delete(obj)method. Called when object is cleared or destroyed. Used for cleanup (e.g., closing files). -
Property Validation: Enforce data types/size in property definitions.
properties ValidatedProp (1,1) double {mustBePositive} = 1; end
3.3 Inheritance & Class Hierarchies
classdef SubClass < SuperClass
methods
function out = method1(obj) % Override
out = 'SubClass version';
end
end
end
-
Single Inheritance Only: MATLAB does not support multiple inheritance.
-
Abstract Classes/Methods: Cannot be instantiated.
Abstractmethods must be implemented by subclasses.methods (Abstract) out = mustImplement(obj); end -
Sealed Classes:
classdef (Sealed) MyClassprevents subclassing. -
superReference: Call superclass method from subclass:out = super.method1(obj).
3.4 Handle vs. Value Classes
| Feature | Handle Class | Value Class |
|---|---|---|
| Inheritance | Inherit from handle |
Inherit from value (default) |
| Assignment | h2 = h1; creates reference (both point to same object) |
v2 = v1; creates independent copy |
| Function Args | Passed by reference (modifications persist) | Passed by value (copy on write) |
| Use Case | GUI components, graphics objects, objects with identity | Simple data structures, mathematical objects |
[!TIP] Rule of Thumb: If you need two variables to refer to the same object and see changes made through either, inherit from
handle. Otherwise, use value classes.
3.5 Events, Listeners & Dynamic Properties
-
Events & Listeners: Implement publish-subscribe pattern.
events ValueChanged end methods function changeValue(obj, newVal) obj.Value = newVal; notify(obj, 'ValueChanged'); % Trigger event end end % Listener setup: % addlistener(obj, 'ValueChanged', @callback); -
Dynamic Properties: Add properties to an object instance at runtime using
addprop.p = addprop(obj, 'DynamicProp'); p.Hidden = true;
4.0 Advanced Graphics & Visualization
4.1 Advanced 2D/3D Plotting
-
Surfaces/Meshes:
surf(Z),mesh(X,Y,Z),contour3(X,Y,Z),slice(X,Y,Z,V, xs,ys,zs). -
Volume Visualization:
isosurface(V, isovalue),patch,volshow(for volumetric data). -
Specialized 3D:
scatter3(X,Y,Z,S,C),stem3(X,Y,Z),quiver3(X,Y,Z,U,V,W).
4.2 Customizing Graphics Objects
-
Graphics Object Hierarchy: Figure → Axes → Plot objects (line, surface, etc.). Use
findobjandfindallto locate objects. -
Deep vs. Shallow Copy:
copyobjcreates shallow copy by default (shared properties). Usesetto modify specific object properties without affecting others. -
Grouping:
hggroupandhgtransformfor grouping and transforming multiple graphics objects together.
4.3 Lighting, Material & Camera Control
-
Lighting:
light('Position',[x y z]),lighting phong/gouraud/flat. -
Material:
material shiny/dull/metallic. Controls reflectance properties. -
Camera: Properties of axes:
CameraPosition,CameraTarget,CameraUpVector. -
Camera Tools:
camzoom(factor),camorbit(dtheta, dphi),camdolly.
4.4 Animations & Movies
-
Frame-by-Frame: Update plot data inside a loop and call
drawnow limitrateto refresh display.for t = 0:0.01:10 y = sin(2*pi*t); set(lineHandle, 'YData', y); drawnow; end -
Creating Videos: Use
VideoWriter(preferred over deprecatedmovie2avi).v = VideoWriter('animation.mp4', 'MPEG-4'); open(v); for i = 1:N % Update plot... frame = getframe(gcf); writeVideo(v, frame); end close(v);
4.5 Interactive Graphics Tools
-
Programmatic Control:
zoom on/off,pan on/off,rotate3d on/off. -
Data Cursor:
dcm = datacursormode(gcf);ConfigureUpdateFcnfor custom display. -
Brushing & Linking:
brush onenables brushing. Uselinkaxesorlinkpropto synchronize multiple axes.
5.0 Performance Optimization & Code Execution
5.1 Code Profiling & Bottleneck Identification
-
Profiler:
profile on -history→ run code →profile viewer. -
Report Shows: Total time, self time, function calls, and line-by-line execution time (most critical for finding slow lines).
5.2 Vectorization & Array Operations
-
Goal: Replace
for/whileloops with array operations using built-in functions. -
Techniques:
-
Logical Indexing:
A(A > 0) = 0; -
Linear Indexing:
A(:)orA(sub2ind(...)). -
Array Operations:
.*,./,.^,sum(A,dim),bsxfun(or implicit expansion in R2016b+).
-
-
arrayfun/cellfun: Can improve readability but often not faster than a vectorized loop. Use for code clarity when operation is not easily vectorizable.
5.3 Memory Management & Preallocation
-
Preallocation: Always preallocate arrays before loops. Use
zeros,NaN,false, oroneswith final size.A = zeros(1000, 1000); % Preallocate for i = 1:1000 A(i,:) = someOperation(i); % No resizing end\boxed{\text{Failure to preallocate is a leading cause of slow MATLAB code.}}
-
Memory Inspection:
whosshows variable size in bytes.classshows data type. -
Clear Variables:
clear varNameorclearvars -except keep1 keep2. -
Memory Mapping:
memmapfilefor accessing large files without loading into memory.
5.4 MEX Files & External Language Integration
-
Purpose: Compile C/C++/Fortran code into a MATLAB-callable function (
mexFunction) for significant speedup in compute-intensive loops. -
Workflow:
-
Write C/C++ source with
mexFunctionsignature. -
Compile in MATLAB:
mex myfunc.c. -
Call like any MATLAB function:
result = myfunc(arg1, arg2);.
-
-
Data Exchange: Use
mxArrayAPI in C code to access MATLAB arrays.
5.5 Parallel & Distributed Computing (Overview)
-
parfor: Parallelfor-loop. Iterations executed concurrently on workers in a parallel pool.parpool(4); % Start 4 workers parfor i = 1:100 results(i) = heavyComputation(i); end[!TIP] Constraint:
parforloop iterations must be independent (no data dependencies between iterations). -
spmd: Single Program Multiple Data. Each worker executes the same code but can have different data. -
GPU Computing:
gpuArraytransfers data to GPU. Many built-in functions support GPU arrays (plus,mtimes,fft). Usegatherto retrieve results.
6.0 Interoperability & External Interfaces
6.1 Python Integration
-
Calling Python:
py.module.function(args).py.sys.path.append('path/to/module'); np = py.importlib.import_module('numpy'); arr = np.array([1,2,3]); -
Type Conversion: Automatic for many types (numeric, char, logical). Complex types (lists, dicts) become Python objects; use
cell,struct, orpy.dictfor conversion. -
Python Environment: Configure via Preferences > Python or
pyenv.
6.2 Java & .NET Integration
-
Java: Create objects with
javaObject('className')orclassName(). Use Java methods directly.list = java.util.ArrayList(); list.add('item'); -
.NET: Load assembly:
NET.addAssembly('MyAssembly.dll'). Create .NET objects. -
MATLAB as COM Server: Can be controlled from external apps (less common).
6.3 COM/ActiveX Automation
-
Connect to COM Server:
h = actxserver('ProgID');(e.g.,'Excel.Application'). -
Control External App: Use dot notation to call methods/properties.
excel = actxserver('Excel.Application'); excel.Workbooks.Add; excel.Range('A1').Value = 42;
6.4 Database Connectivity
-
Toolbox: Database Toolbox required for ODBC/JDBC.
-
Connection:
conn = database(datasource, username, password);. -
Querying:
data = fetch(conn, 'SELECT * FROM table');. -
Updates:
exec(conn, 'INSERT ...'). Manage transactions withcommit/rollback.
7.0 Deployment, Packaging & Sharing
7.1 MATLAB Compiler & Runtime
-
mcc: Command-line compiler.mcc -m myapp.m % Create standalone executable -
Application Compiler App (
deploytool): GUI for packaging, including adding files, setting icons, etc. -
MATLAB Runtime (MCR): Must be installed on target machine. Free redistributable. Version must match MATLAB version used for compilation.
7.2 Web Applications & Server Deployment
-
Web Apps: Created in App Designer. Deployed to MATLAB Web App Server (requires license). Users access via browser.
-
MATLAB Production Server: For scalable, secure deployment of functions (not GUIs) as services. Clients call via RESTful API or
matlab.production.serverclient.
7.3 Toolboxes & Add-Ons
-
Custom Toolbox (
.mltbx): Package functions, classes, apps, documentation. Created via Package Toolbox tool. -
Add-On Explorer: Browse and install toolboxes from MathWorks File Exchange or internal repositories.
-
Dependencies: Toolbox
prjfile manages included files and dependencies.
7.4 Code Generation (Overview)
-
MATLAB Coder: Generate C/C++ code from MATLAB algorithms (subset of MATLAB language supported). Requires MATLAB Coder license.
codegen myfunc -args {0} % Generate C code -
Simulink Coder: For Simulink models.
-
Limitations: Not all MATLAB functions supported. Must use fixed-size arrays, avoid dynamic features. Generated code is for integration into external applications, not for running in MATLAB.