Lesson 05-Programming Techniques

Vectorized Operations and Performance Optimization

Vectorized Operations Replacing Loops

Basic Vectorization Examples:

% Inefficient loop method
n = 1e6;
result = zeros(1,n);
for i = 1:n
    result(i) = sin(i/100);
end

% Efficient vectorized implementation
x = (1:n)/100;
result = sin(x);  % Speed improvement over 100 times

Matrix Operation Optimization:

% Matrix multiplication replacing element-wise operations
A = rand(1000);
B = rand(1000);

% Inefficient method
C = zeros(1000);
for i = 1:1000
    for j = 1:1000
        C(i,j) = A(i,j) * B(i,j);
    end
end

% Efficient matrix operations
C = A .* B;  % Element-wise multiplication
D = A * B;   % Matrix multiplication

Broadcasting Mechanism Application:

% Operations on arrays of different dimensions
A = rand(100,1);
B = rand(1,100);

% Automatic dimension expansion
C = A + B;  % Broadcasts to 100×100 matrix

% Explicit dimension expansion
A_exp = repmat(A,1,100);
B_exp = repmat(B,100,1);
C_alt = A_exp + B_exp;  % Equivalent result

Advanced Vectorization Techniques

Logical Indexing Optimization:

% Data filtering and processing
data = randn(1e6,1);
threshold = 2;

% Inefficient method
outliers = [];
for i = 1:length(data)
    if abs(data(i)) > threshold
        outliers = [outliers; data(i)];
    end
end

% Efficient logical indexing
outliers = data(abs(data) > threshold);  % Direct extraction

Multi-Condition Vectorization:

% Complex condition filtering
x = randn(1e6,1);
y = randn(1e6,1);

% Inefficient loop
valid = false(1e6,1);
for i = 1:1e6
    if x(i)^2 + y(i)^2 < 1 && x(i) > 0
        valid(i) = true;
    end
end

% Efficient vectorization
valid = (x.^2 + y.^2 < 1) & (x > 0);
filtered_data = [x(valid), y(valid)];

Memory Management Techniques

Preallocation of Arrays

Numerical Array Preallocation:

% Wrong method (dynamic growth)
result = [];
for i = 1:1e6
    result(i) = i^2;  % Reallocates memory on each iteration
end

% Correct preallocation method
result = zeros(1,1e6);  % Preallocate memory
for i = 1:1e6
    result(i) = i^2;    % Directly fill preallocated memory
end

Multi-Dimensional Array Preallocation:

% Preallocate 3D array
dims = [100, 200, 50];
volume = zeros(dims);  % 100×200×50 array

% Preallocate cell array
cell_array = cell(100,1);  % Array with 100 cells
for i = 1:100
    cell_array{i} = rand(10,10);
end

Structure Array Preallocation:

% Preallocate structure array
n = 1e4;
particles = struct('position', [], 'velocity', [], 'mass', []);

% Preallocate fields
particles(1:n).position = zeros(n,3);
particles(1:n).velocity = zeros(n,3);
particles(1:n).mass = zeros(n,1);

% Fill data
for i = 1:n
    particles(i).position = rand(1,3);
    particles(i).velocity = rand(1,3)*10;
    particles(i).mass = rand*100;
end

Memory Optimization Strategies

Sparse Matrix Application:

% Sparse matrix creation
n = 1e4;
A = sprandn(n,n,0.001);  % 0.1% non-zero elements

% Sparse matrix operations
b = randn(n,1);
x = A \ b;  % Automatically uses sparse solver

% Convert to full matrix (use cautiously)
A_full = full(A);  % Extremely memory-intensive

Memory-Efficient Data Types:

% Data type optimization
large_array = rand(1e6,1);

% Default double precision (8 bytes)
size_double = whos('large_array');

% Single precision (4 bytes)
large_array_single = single(large_array);
size_single = whos('large_array_single');

% Unsigned integer (1-4 bytes)
counts = uint32(randi([0,100],1e6,1));
size_uint = whos('counts');

Advanced Data Structures

Cell Arrays

Cell Array Creation and Access:

% Create cell array
cell_array = cell(3,2);  % 3×2 cells

% Fill with different types of data
cell_array{1,1} = 'Tom';
cell_array{1,2} = [1,2,3];
cell_array{2,1} = rand(3);
cell_array{2,2} = struct('a',1,'b',2);
cell_array{3,1} = @(x) x^2;
cell_array{3,2} = @sin;

% Access cell contents
str = cell_array{1,1};
mat = cell_array{2,1};

Advanced Cell Array Operations:

% Convert cells to matrix
cell_data = {rand(3), rand(3), rand(3)};
matrix_data = cell2mat(cell_data);  % Requires consistent dimensions in cells

% Cell array concatenation
cell_row = [cell_array(1,:), cell_array(2,:)];  % Horizontal concatenation
cell_col = [cell_array(:,1); cell_array(:,2)];  % Vertical concatenation

% Apply functions to cells
cell_fun = {@(x)x^2, @(x)exp(x), @(x)log(x)};
results = cellfun(@(f)f(2), cell_fun);  % Evaluate each function at x=2

Struct Arrays

Structure Creation and Access:

% Create structure array
particles(1).position = [0,0,0];
particles(1).velocity = [1,0,0];
particles(1).mass = 1;

particles(2).position = [1,1,1];
particles(2).velocity = [0,1,0];
particles(2).mass = 2;

% Batch create structure array
n = 100;
particles = struct('position', zeros(n,3), ...
                   'velocity', zeros(n,3), ...
                   'mass', zeros(n,1));

% Fill data
for i = 1:n
    particles(i).position = rand(1,3);
    particles(i).velocity = rand(1,3);
    particles(i).mass = rand;
end

Advanced Struct Array Operations:

% Structure field operations
fields = fieldnames(particles);  % Get all field names
positions = [particles.position];  % Extract all position data

% Structure array filtering
heavy_particles = particles([particles.mass] > 0.5);

% Structure array sorting
[~,idx] = sort([particles.mass]);
sorted_particles = particles(idx);

Function Handling Techniques

Anonymous Functions

Basic Anonymous Functions:

% Create simple anonymous function
square = @(x) x^2;
result = square(5);  % 25

% Multi-variable anonymous function
circle_area = @(r) pi * r^2;
a = circle_area(3);  % 28.2743

% Anonymous function with parameters
adder = @(x, y) x + y;
sum_result = adder(3,4);  % 7

Nested Anonymous Functions:

% Nested function creation
integration = @(a,b) ...
    integral(@(x) x.^2 + a*x + b, 0, 1);

result = integration(2,3);  % Compute ∫(x²+2x+3)dx from 0 to 1

% More complex nesting
filter_func = @(data, threshold) ...
    data(arrayfun(@(x) x > threshold, data));

Anonymous Function Application Scenarios:

% Function handle array
funcs = {@(x)x^2, @(x)sin(x), @(x)exp(x)};
results = cellfun(@(f)f(2), funcs);  % Evaluate at x=2

% Callback function definition
button_callback = @(src,event)disp('Button clicked!');
uicontrol('Style','pushbutton', 'Callback', button_callback);

% Parameterized function generation
make_multiplier = @(factor) @(x) x * factor;
double = make_multiplier(2);
triple = make_multiplier(3);

Function Handles

Function Handle Basics:

% Create function handle
sin_handle = @sin;
result = sin_handle(pi/2);  % 1

% Function handle array
func_array = {@(x)x^2, @sin, @cos};
apply_funcs = @(x) cellfun(@(f)f(x), func_array);

% Function handle as parameter
function y = apply_func(f, x)
    y = f(x);
end
result = apply_func(@sqrt, 4);  % 2

Advanced Function Handle Applications:

% Partial function application
function y = add(a,b)
    y = a + b;
end

add_five = @(x) add(5, x);  % Fix first parameter
result = add_five(3);       % 8

% Function composition
function y = compose(f,g,x)
    y = f(g(x));
end

square_after_sin = @(x) compose(@(y)y^2, @sin, x);
result = square_after_sin(pi/6);  % (sin(π/6))^2 = 0.25

Function Handles with OOP:

% Class method handle
obj = MyClass();
method_handle = @obj.myMethod;
result = method_handle(42);

% Static method handle
static_handle = @MyClass.staticMethod;
result = static_handle(42);

Comprehensive Application Cases

High-Performance Image Processing Pipeline

% 1. Batch image loading
image_files = dir('images/*.jpg');
n = length(image_files);
images = cell(n,1);

% Preallocate memory
for i = 1:n
    images{i} = imread(fullfile(image_files(i).folder, image_files(i).name));
end

% 2. Parallel processing
parfor i = 1:n
    % 3. Vectorized color conversion
    img = images{i};
    if size(img,3) == 3
        img_gray = rgb2gray(img);
    else
        img_gray = img;
    end
    
    % 4. Anonymous function for local operations
    enhance = @(x) imadjust(x, stretchlim(x), []);
    img_enhanced = enhance(img_gray);
    
    % 5. Structure to store results
    results(i).original = img;
    results(i).processed = img_enhanced;
end

% 6. Batch saving
output_dir = 'processed/';
if ~exist(output_dir, 'dir')
    mkdir(output_dir);
end
parfor i = 1:n
    imwrite(results(i).processed, fullfile(output_dir, sprintf('processed_%03d.jpg', i)));
end

Scientific Computing Optimization Example

% 1. Parameterized simulation setup
params = struct(...
    'dt', 0.01, ...
    'tspan', [0 10], ...
    'mass', 1.0, ...
    'damping', 0.1);

% 2. Vectorized ODE definition
ode_fun = @(t,y) [
    y(2); 
    (-params.damping*y(2) - params.mass*9.8)/params.mass
];

% 3. Preallocate result storage
n_steps = ceil((params.tspan(2)-params.tspan(1))/params.dt);
results = struct('t', zeros(n_steps,1), 'y', zeros(n_steps,2));

% 4. Solve using ode45 (note time vector handling)
[t_ode, y_ode] = ode45(ode_fun, params.tspan, [0; 0]);

% 5. Interpolate to uniform time grid
results.t = linspace(params.tspan(1), params.tspan(2), n_steps);
results.y = interp1(t_ode, y_ode, results.t);

% 6. Vectorized post-processing
kinetic_energy = 0.5 * params.mass * results.y(:,2).^2;
potential_energy = params.mass * 9.8 * results.y(:,1);
total_energy = kinetic_energy + potential_energy;

% 7. Plotting optimization
figure;
subplot(2,1,1);
plot(results.t, results.y(:,1));
xlabel('Time (s)'); ylabel('Position (m)');

subplot(2,1,2);
plot(results.t, [kinetic_energy, potential_energy, total_energy]);
legend('Kinetic', 'Potential', 'Total');
xlabel('Time (s)'); ylabel('Energy (J)');

By mastering these core techniques, you will be able to:

  1. Develop high-performance scientific computing programs
  2. Build complex data processing pipelines
  3. Implement memory-efficient algorithms
  4. Design flexible functional programming structures
  5. Optimize large-scale numerical simulations
  6. Handle complex engineering computation problems
  7. Create maintainable MATLAB code libraries

Share your love