Lesson 13-MATLAB Programming Fundamentals and Algorithm Implementation

MATLAB Programming Structure

Control Flow Statements

Composite Conditional Control Example:

% Multi-condition judgment (if-elseif-else)
score = 85;
if score >= 90
    grade = 'A';
elseif score >= 80
    grade = 'B';
elseif score >= 70
    grade = 'C';
else
    grade = 'D';
end

% switch-case structure (handling discrete values)
day = 3;
switch day
    case 1
        disp('Monday');
    case 2
        disp('Tuesday');
    case {3,4,5}
        disp('Weekday');
    otherwise
        disp('Weekend');
end

% Vectorized alternative to loops (avoid explicit for loops)
n = 1e6;
x = randn(n,1);
y = zeros(n,1);  % Pre-allocate memory

% Traditional loop method (not recommended)
% for i = 1:n
%     y(i) = x(i)^2 + 2*x(i) + 1;
% end

% Vectorized operation (recommended)
y = x.^2 + 2*x + 1;  % Fully vectorized

% while loop control
tolerance = 1e-6;
max_iter = 1000;
iter = 0;
x = 1.0;  % Initial guess

while abs(x^2 - 2) > tolerance && iter < max_iter
    x = (x + 2/x)/2;  % Newton iteration method
    iter = iter + 1;
end
fprintf('Square root approximate solution: %.6f (iterations: %d)\n', x, iter);

Function Definition and Calling

Various Function Definition Methods:

% Anonymous function (quickly define simple functions)
square = @(x) x.^2;
result = square(5);  % Call anonymous function

% Nested function (define function inside function)
function outerFunc()
    a = 10;
    
    function innerFunc(b)
        c = a + b;  % Access outer function variable
        disp(c);
    end
    
    innerFunc(5);  % Call nested function
end

% Subfunction (defined in script or function file)
function mainFunction()
    result = calculateSum(1, 2);
    disp(result);
    
    function s = calculateSum(x, y)
        s = x + y;
    end
end

% Variable input/output function
function varargout = flexibleFunction(varargin)
    % varargin receives variable inputs
    % varargout returns variable outputs
    
    numInputs = nargin;
    numOutputs = nargout;
    
    if numOutputs == 0
        disp('No output requested');
    else
        for k = 1:numOutputs
            varargout{k} = varargin{k}^2;  % Example calculation
        end
    end
end

Error Handling Mechanisms

Robust Error Handling Example:

% Basic try-catch structure
try
    data = load('nonexistent_file.mat');
catch ME
    fprintf('Error type: %s\n', ME.identifier);
    fprintf('Error message: %s\n', ME.message);
    
    % Create default data
    data = struct('value', 0, 'timestamp', datetime('now'));
end

% Nested try-catch
try
    fileID = fopen('data.txt', 'r');
    try
        data = fscanf(fileID, '%f');
    catch ME_inner
        fprintf('File read error: %s\n', ME_inner.message);
        data = [];
    end
    fclose(fileID);
catch ME_outer
    fprintf('File open error: %s\n', ME_outer.message);
    data = [];
end

% Custom error throwing
function validateInput(x)
    if x < 0
        error('Input value must be non-negative: x = %.2f', x);
    end
    if ~isnumeric(x)
        error('Input must be numeric type');
    end
end

% Call example
try
    validateInput(-5);
catch ME
    fprintf('Input validation failed: %s\n', ME.message);
end

Debugging Techniques

Interactive Debugging Methods:

% Set breakpoints (three ways)
% 1. Click left of line number in editor
% 2. Use dbstop command
dbstop in myFunction at 15  % Set breakpoint at line 15 in myFunction
dbstop if error             % Automatically pause on error

% Debugging command examples
dbstep                      % Execute next line
dbcont                      % Continue to next breakpoint
dbup                        % Switch to calling function workspace
dbdown                      % Return to called function workspace
dbquit                      % Quit debugging mode

% Example debugging scenario
function y = problematicFunction(x)
    y = x^2;
    z = 1/y;  % Possible division by zero (set breakpoint on line 3)
    y = y + z;
end

% Call function to enter debugging
try
    result = problematicFunction(0);
catch
    % Automatically enter debugging mode on error (due to dbstop if error)
end

Code Optimization Techniques

Performance-Critical Code Optimization:

% Memory pre-allocation comparison
% Inefficient way (dynamic array growth)
n = 1e6;
slow_array = [];
for i = 1:n
    slow_array(i) = rand();
end

% Efficient way (pre-allocate memory)
fast_array = zeros(n,1);
for i = 1:n
    fast_array(i) = rand();
end

% Vectorized alternative to loops (matrix operations)
% Compute matrix exponential
A = randn(1000);
% Inefficient way
% expA = zeros(1000);
% for i = 1:1000
%     for j = 1:1000
%         expA(i,j) = exp(A(i,j));
%     end
% end

% Efficient vectorization
expA = exp(A);  % Fully vectorized

% Use bsxfun for broadcasting operations (older MATLAB versions)
% Newer versions support implicit expansion
A = rand(1000,1);
B = rand(1,1000);
% C = bsxfun(@plus, A, B);  % Older version
C = A + B;                 % Newer version implicit expansion

Data Structures and Algorithms

Array and Matrix Operations

Advanced Matrix Transformation Techniques:

% Multidimensional array reshaping
A = rand(4,5,3);
B = reshape(A, [10,6]);  % Keep total elements unchanged (4 * 5 * 3 = 10 * 6)

% Matrix replication and concatenation
C = repmat(A, [2 3 1]);  % Replicate 2 times in rows, 3 times in columns

% Efficient matrix concatenation
D = cat(3, A, A);  % Concatenate along third dimension

% Special matrix generation
magic_mat = magic(5);      % Magic square
hilbert_mat = hilb(4);     % Hilbert matrix
pascal_mat = pascal(5);    % Pascal matrix

% Advanced matrix indexing techniques
M = magic(5);
rows = [1 3 5];
cols = [2 4];
submatrix = M(rows, cols);  % Get submatrix of specified rows and columns

% Logical indexing application
large_values = M(M > 10);  % Extract elements greater than 10

Structures and Cell Arrays

Complex Data Organization Example:

% Structure array creation and access
patients(1).name = 'John';
patients(1).age = 35;
patients(1).BP = [120 80];

patients(2).name = 'Mary';
patients(2).age = 42;
patients(2).BP = [118 76];

% Batch operations on structure fields
ages = [patients.age];  % Extract all ages into array

% Cell array creation
data_cell = {rand(3), 'text data', magic(4), patients};

% Cell array access
first_matrix = data_cell{1};  % Get first element (matrix)
second_element = data_cell{2}; % Get text data

% Mixed use of structures and cells
experiment.results = rand(10,1);
experiment.metadata = struct('date', datetime('now'), 'operator', 'Alice');
experiment.notes = {'Initial run', 'Needs verification'};

% Cell function application (cellfun)
cell_array = {@(x)x^2, @(x)x^3, @(x)sin(x)};
results = cellfun(@(f)f(2), cell_array);  % Compute f(2) for each function

Sorting and Search Algorithms

Efficient Data Retrieval Techniques:

% Various sorting methods
unsorted_vec = rand(1,100);
ascending_order = sort(unsorted_vec);          % Default ascending
descending_order = sort(unsorted_vec, 'descend'); % Descending

% Structure array sorting
patients(1).age = 35;
patients(2).age = 42;
patients(3).age = 28;
[sorted_patients, idx] = sortStructArray(patients, 'age');

% Custom sorting function
function sorted = sortStructArray(S, field)
    values = [S.(field)];
    [~, idx] = sort(values);
    sorted = S(idx);
end

% Find element positions
logical_idx = ismember([1 2 3], [3 1 4]);  % Returns [1 0 1]

% Find specific value position
data = [5 3 7 1 9];
value = 7;
pos = find(data == value);  % Returns 3 (1-based indexing)

% Fuzzy search (within tolerance)
tolerance = 0.1;
target = 3.14;
approx_pos = find(abs(data - target) < tolerance);

Matrix Decomposition

Numerical Linear Algebra Applications:

% LU decomposition (solving linear systems)
A = [4 3; 6 3];
b = [1; 2];
[L,U] = lu(A);          % LU decomposition
y = L \ b;              % Forward substitution
x = U \ y;              % Backward substitution

% QR decomposition (least squares problems)
A = randn(10,3);
b = randn(10,1);
[Q,R] = qr(A);          % Economy QR decomposition
x = R \ (Q' * b);       % Least squares solution

% SVD decomposition (low-rank matrix approximation)
A = randn(100,50);
[U,S,V] = svd(A);       % Full SVD
k = 5;                  % Keep top 5 singular values
A_approx = U(:,1:k) * S(1:k,1:k) * V(:,1:k)';  % Low-rank approximation

% Eigenvalue decomposition
symmetric_mat = gallery('lehmer',5);  % Generate symmetric matrix
[eigvecs, eigvals] = eig(symmetric_mat);
eigenvalues = diag(eigvals);

% Sparse matrix decomposition
n = 1000;
A_sparse = sprandn(n,n,0.01);  % 1% nonzero elements
[L_sparse,U_sparse,P,Q,R] = lu(A_sparse);  % Sparse LU decomposition

Numerical Integration and Differentiation

Scientific Computing Function Applications:

% Numerical integration method comparison
f = @(x) sin(x).^2;
a = 0; b = pi;

% Trapezoidal rule
trapz_result = trapz(linspace(a,b,1000), f(linspace(a,b,1000)));

% quad function (adaptive Simpson)
quad_result = quad(f, a, b);

% integral function (recommended)
integral_result = integral(f, a, b);

% Highly oscillatory function integration
oscillatory_f = @(x) sin(100*x)./x;
integral_osc = integral(oscillatory_f, 0, 1, 'AbsTol', 1e-12);

% Numerical differentiation
x = linspace(0,2*pi,100);
y = sin(x);

% Finite difference method
dy_fd = diff(y)./diff(x);  % First-order derivative approximation

% gradient function (central difference)
dy_grad = gradient(y,x);    % More accurate gradient computation

% Higher-order derivatives
d2y_dx2 = diff(y,2)./diff(x,2);  % Second-order derivative approximation

File and Data Interaction

File I/O Operations

Structured File Read/Write:

% Text file writing
data = rand(5,3);
fileID = fopen('data.txt', 'w');
fprintf(fileID, 'Matrix Data:\n');
fprintf(fileID, '%.4f\t%.4f\t%.4f\n', data');  % Transpose before writing
fclose(fileID);

% Text file reading
fileID = fopen('data.txt', 'r');
header = fgetl(fileID);  % Read header line
data_read = fscanf(fileID, '%f', [3 5])';  % Read matrix data
fclose(fileID);

% Binary file efficient storage
fid = fopen('binary_data.bin', 'w');
fwrite(fid, data, 'double');  % Write as double precision
fclose(fid);

% Binary file reading
fid = fopen('binary_data.bin', 'r');
loaded_data = fread(fid, [3 5], 'double');
fclose(fid);

% MAT file storage (preserve variable names)
save('data.mat', 'data', '-v7.3');  % Support files larger than 2GB
loaded_vars = load('data.mat');     % Automatically load all variables

Database Connection

SQL Database Interaction:

% Establish database connection
conn = database('myDB', 'username', 'password', ...
    'Vendor', 'MySQL', 'Server', 'localhost');

% Check connection status
if isopen(conn)
    disp('Database connection successful');
else
    error('Connection failed: %s', conn.Message);
end

% Execute SQL query
sqlquery = 'SELECT * FROM employees WHERE department = ''IT''';
curs = exec(conn, sqlquery);
curs = fetch(curs);  % Fetch results
data = curs.Data;    % Result data

% Parameterized query (prevent SQL injection)
dept = 'HR';
sqlquery = 'SELECT * FROM employees WHERE department = ?';
curs = exec(conn, sqlquery, dept);
data = fetch(curs).Data;

% Write to database
insert(conn, 'employees', {'name','salary'}, {'John Doe', 75000});

% Close connection
close(curs);
close(conn);

Network Data Acquisition

Web Data Interaction Example:

% Read web page content
url = 'https://www.mathworks.com';
webContent = webread(url);  % Automatically parse JSON/XML

% RESTful API request
apiKey = 'your_api_key';
endpoint = ['https://api.example.com/data?key=', apiKey];
options = weboptions('Timeout', 10);
responseData = webread(endpoint, options);

% Download file
fileURL = 'https://example.com/data.csv';
localFile = 'downloaded_data.csv';
websave(localFile, fileURL);

% Submit form data
data = struct('username', 'user123', 'password', 'pass123');
response = webwrite('https://api.example.com/login', data);

% Process JSON data
jsonStr = '{"name":"John","age":30,"city":"New York"}';
jsonData = jsondecode(jsonStr);
name = jsonData.name;
age = jsonData.age;

% Generate JSON
dataOut = struct('temperature', 23.5, 'humidity', 45);
jsonOutput = jsonencode(dataOut);
fid = fopen('output.json', 'w');
fprintf(fid, '%s', jsonOutput);
fclose(fid);

Data Serialization

Efficient Data Storage Formats:

% JSON serialization
data = struct('experiment', 'physics', 'results', rand(10,1), ...
    'metadata', struct('date', datetime('now'), 'operator', 'Alice'));
jsonStr = jsonencode(data);
fid = fopen('experiment.json', 'w');
fprintf(fid, '%s', jsonStr);
fclose(fid);

% MAT file version control
save('data_v7.mat', 'data');          % Traditional MAT file format
save('data_v7.3.mat', 'data', '-v7.3'); % HDF5 format supporting large data

% HDF5 advanced operations
h5create('dataset.h5', '/group1/dataset1', [100 100], 'Datatype', 'double');
data = rand(100);
h5write('dataset.h5', '/group1/dataset1', data);
read_data = h5read('dataset.h5', '/group1/dataset1');

% Protocol Buffers integration (requires additional toolbox)
% protoFile = 'message.proto';
% protoc = 'protoc --matlab_out=. message.proto';
% system(protoc);
% msg = Message();  % Use generated class
% msg.Field1 = 'value';
% saveProto('message.pb', msg);

Parallel Computing Fundamentals

Parallel Programming Techniques:

% parfor parallel loop
n = 1e6;
results = zeros(n,1);

% Parallel computation of squares
parfor (i = 1:n, 4)  % Use 4 workers
    results(i) = i^2;
end

% Independent task parallel (parfeval)
f = parfeval(@sqrt, 1, 25);  % Asynchronously execute sqrt(25)
result = fetchOutputs(f);    % Retrieve result

% Batch mode (parbatch)
job = batch(@myScript, 1, {'input1', 'input2'}, ...
    'Pool', 4, 'AttachedFiles', {'datafile.mat'});

% Wait for job completion
wait(job);
results = load(job.OutputArguments{1});

% Parallel pool management
pool = gcp('nocreate');  % Do not create new pool
if isempty(pool)
    parpool('local',4);  % Start 4 workers
end

% Distributed arrays (large-scale data)
distData = distributed(rand(1e7,1));  % Data distributed across cluster memory
meanValue = mean(distData);          % Distributed mean computation
Share your love