MATLAB

#24
TIOBE#17
PYPL#14
GitHub#51
IEEESpectrum#24
programming languagenumerical computingscientific computingengineeringdata analysissignal processing

Programming Language

MATLAB

Overview

MATLAB is a high-level programming language and interactive environment for numerical computation, data analysis, and algorithm development.

Details

MATLAB (Matrix Laboratory) is a scientific computing programming language and environment developed by MathWorks in 1984, optimized for numerical computation processing centered on matrix operations. It is widely used in engineering, scientific research, financial analysis, medical imaging, and other fields, providing rich built-in functions, specialized toolboxes, and visualization capabilities. Its intuitive syntax and interactive environment enable efficient execution of complex mathematical calculations and data analysis, suitable for everything from prototyping to full-scale application development. Through integration with Simulink, it is also widely used in model-based design and control system development.

Code Examples

Hello World

% Basic output
disp('Hello, World!')

% Output using variables
message = 'Hello, MATLAB!';
disp(message)

% Formatted output
name = 'John';
age = 25;
fprintf('My name is %s and I am %d years old.\n', name, age)

% Numerical output
pi_value = pi;
fprintf('Pi: %.4f\n', pi_value)

% Multiple variables
x = 10;
y = 20;
result = x + y;
fprintf('%d + %d = %d\n', x, y, result)

Variables and Basic Data Types

% Scalar variables
number = 42;
float_num = 3.14159;
complex_num = 3 + 4i;
logical_val = true;

% Strings
str1 = 'Single quote string';
str2 = "Double quote string";

% Vectors (1D arrays)
row_vector = [1, 2, 3, 4, 5];
column_vector = [1; 2; 3; 4; 5];
range_vector = 1:5;  % 1 to 5
range_step = 0:0.5:2;  % 0 to 2 with 0.5 step

% Matrices (2D arrays)
matrix_2x3 = [1, 2, 3; 4, 5, 6];
identity_matrix = eye(3);  % 3x3 identity matrix
zeros_matrix = zeros(2, 4);  % 2x4 zero matrix
ones_matrix = ones(3, 3);  % 3x3 all-ones matrix
random_matrix = rand(3, 3);  % 3x3 random matrix

% Cell arrays
cell_array = {'string', 42, [1, 2, 3]};
cell_array{1} = 'new string';

% Structures
person.name = 'John Doe';
person.age = 30;
person.scores = [85, 92, 78];

disp(['Number: ', num2str(number)]);
disp(['Matrix size: ', num2str(size(matrix_2x3))]);
disp(['Complex number: ', num2str(complex_num)]);

Conditional Statements

% Basic if statement
score = 85;

if score >= 90
    grade = 'A';
elseif score >= 80
    grade = 'B';
elseif score >= 70
    grade = 'C';
else
    grade = 'D';
end

fprintf('Score: %d, Grade: %s\n', score, grade);

% Multiple condition combinations
age = 20;
has_license = true;

if age >= 18 && has_license
    disp('You can drive');
elseif age >= 18
    disp('Please get a license');
else
    disp('Please get a license after turning 18');
end

% switch statement
day = 'Wednesday';
switch day
    case 'Monday'
        disp('Start of the week');
    case 'Wednesday'
        disp('Midweek');
    case 'Friday'
        disp('Almost weekend');
    otherwise
        disp('Other day');
end

% Logical operators
value = 10;
if value > 5 && value < 15
    disp('Greater than 5 and less than 15');
end

if value == 10 || value == 20
    disp('Value is 10 or 20');
end

Arrays and Matrices

% Vector creation and manipulation
fruits = {'apple', 'banana', 'orange'};
fruits{end+1} = 'grape';  % Add element

% Numerical array operations
numbers = [1, 2, 3, 4, 5];
numbers(end+1) = 6;  % Add element
numbers(2) = 10;     % Change element

% Matrix creation and operations
A = [1, 2, 3; 4, 5, 6; 7, 8, 9];
B = [9, 8, 7; 6, 5, 4; 3, 2, 1];

% Matrix operations
C = A + B;        % Matrix addition
D = A * B;        % Matrix multiplication
E = A .* B;       % Element-wise multiplication
F = A';           % Matrix transpose

% Access specific matrix elements
element = A(2, 3);    % Element at row 2, column 3
row = A(2, :);        % Entire row 2
column = A(:, 1);     % Entire column 1
submatrix = A(1:2, 2:3);  % Submatrix

% Array statistics
mean_val = mean(numbers);
std_val = std(numbers);
max_val = max(numbers);
min_val = min(numbers);

fprintf('Mean: %.2f, Std: %.2f\n', mean_val, std_val);
fprintf('Max: %d, Min: %d\n', max_val, min_val);

% Logical indexing
large_numbers = numbers(numbers > 3);
disp(['Numbers > 3: ', num2str(large_numbers)]);

Loops and Iteration

% for loop (array elements)
fruits = {'apple', 'banana', 'orange'};
for i = 1:length(fruits)
    fprintf('Fruit %d: %s\n', i, fruits{i});
end

% for loop (numerical range)
for i = 1:5
    square = i^2;
    fprintf('%d squared is %d\n', i, square);
end

% while loop
count = 0;
while count < 5
    count = count + 1;
    fprintf('Count: %d\n', count);
end

% Process each element of a matrix
matrix = [1, 2, 3; 4, 5, 6];
for i = 1:size(matrix, 1)  % Loop through rows
    for j = 1:size(matrix, 2)  % Loop through columns
        fprintf('Row%d Col%d: %d\n', i, j, matrix(i, j));
    end
end

% Vectorized operations (recommended)
numbers = 1:10;
squares = numbers.^2;  % Compute squares of all elements at once
disp(['Squares of 1-10: ', num2str(squares)]);

% Find function for conditional search
data = [1, 5, 3, 8, 2, 9, 4];
indices = find(data > 5);
values = data(indices);
fprintf('Values > 5: %s\n', num2str(values));

Function Definition and Calling

% Basic function (save in separate file)
% calculate_area.m
function area = calculate_area(width, height)
    if nargin < 2
        height = 10;  % Default value
    end
    area = width * height;
end

% Function with multiple return values
% stats.m
function [mean_val, std_val, max_val, min_val] = stats(data)
    mean_val = mean(data);
    std_val = std(data);
    max_val = max(data);
    min_val = min(data);
end

% Function calling examples
area1 = calculate_area(5, 8);
area2 = calculate_area(6);  % height uses default value

data = [1, 5, 3, 8, 2, 9, 4];
[m, s, max_v, min_v] = stats(data);
fprintf('Mean: %.2f, Std: %.2f, Max: %d, Min: %d\n', m, s, max_v, min_v);

% Anonymous functions (lambda functions)
square_func = @(x) x.^2;
double_func = @(x) 2 * x;

result1 = square_func(5);
result2 = double_func(10);
fprintf('5 squared: %d, 10 doubled: %d\n', result1, result2);

% Numerical integration example
f = @(x) x.^2 + 2*x + 1;
integral_result = integral(f, 0, 2);
fprintf('Integral result: %.4f\n', integral_result);

Numerical Computing and Plotting

% Basic plotting
x = 0:0.1:2*pi;
y = sin(x);
z = cos(x);

figure;
plot(x, y, 'b-', 'LineWidth', 2);
hold on;
plot(x, z, 'r--', 'LineWidth', 2);
title('Trigonometric Functions');
xlabel('x');
ylabel('y');
legend('sin(x)', 'cos(x)');
grid on;

% 3D plotting
[X, Y] = meshgrid(-2:0.1:2, -2:0.1:2);
Z = X.^2 + Y.^2;

figure;
surf(X, Y, Z);
title('3D Surface Plot');
xlabel('X');
ylabel('Y');
zlabel('Z');
colorbar;

% Statistical plots
data = randn(1000, 1);  % Normal distribution random numbers

figure;
subplot(2, 1, 1);
hist(data, 50);
title('Histogram');

subplot(2, 1, 2);
boxplot(data);
title('Box Plot');

% Numerical computation examples
% Solve linear system Ax = b
A = [2, 1, -1; 1, 3, 2; 1, 0, 1];
b = [8; 13; 5];
x = A \ b;  % Solution to linear system
disp('Linear system solution:');
disp(x);

% Eigenvalues and eigenvectors
[V, D] = eig(A);
disp('Eigenvalues:');
disp(diag(D));

Signal Processing and Filtering

% Signal generation
fs = 1000;  % Sampling frequency
t = 0:1/fs:1-1/fs;  % Time vector

% Composite signal (50Hz + 120Hz + noise)
signal = sin(2*pi*50*t) + 0.5*sin(2*pi*120*t) + 0.2*randn(size(t));

% FFT (Fast Fourier Transform)
Y = fft(signal);
f = (0:length(Y)-1)*fs/length(Y);

% Plotting
figure;
subplot(2, 1, 1);
plot(t(1:200), signal(1:200));
title('Time Domain Signal');
xlabel('Time [s]');
ylabel('Amplitude');

subplot(2, 1, 2);
plot(f(1:length(f)/2), abs(Y(1:length(Y)/2)));
title('Frequency Spectrum');
xlabel('Frequency [Hz]');
ylabel('Amplitude');

% Low-pass filter design
fc = 80;  % Cutoff frequency
[b, a] = butter(4, fc/(fs/2));  % 4th order Butterworth filter

% Filtering
filtered_signal = filter(b, a, signal);

figure;
plot(t(1:500), signal(1:500), 'b', 'LineWidth', 1);
hold on;
plot(t(1:500), filtered_signal(1:500), 'r', 'LineWidth', 2);
title('Filtering Results');
legend('Original Signal', 'Filtered Signal', 'Location', 'best');

Special Features

Simulink Integration

% Simulink model control
model_name = 'my_model';

% Load model
% load_system(model_name);

% Set parameters
% set_param([model_name '/Gain'], 'Gain', '2.5');

% Run simulation
% sim(model_name);

% Get results
% simout = sim(model_name, 'ReturnWorkspaceOutputs', 'on');

disp('Simulink integration functionality');

GUI Creation with App Designer

% Simple GUI application example
function simple_calculator
    % Create figure
    fig = uifigure('Name', 'Simple Calculator', 'Position', [100, 100, 300, 200]);
    
    % Create UI elements
    num1_field = uieditfield(fig, 'numeric', 'Position', [50, 150, 100, 22], 'Value', 0);
    num2_field = uieditfield(fig, 'numeric', 'Position', [170, 150, 100, 22], 'Value', 0);
    
    add_btn = uibutton(fig, 'push', 'Text', 'Add', 'Position', [50, 100, 50, 22]);
    subtract_btn = uibutton(fig, 'push', 'Text', 'Subtract', 'Position', [110, 100, 50, 22]);
    multiply_btn = uibutton(fig, 'push', 'Text', 'Multiply', 'Position', [170, 100, 50, 22]);
    divide_btn = uibutton(fig, 'push', 'Text', 'Divide', 'Position', [230, 100, 50, 22]);
    
    result_field = uieditfield(fig, 'numeric', 'Position', [110, 50, 100, 22], 'Editable', 'off');
    
    % Set callback functions
    add_btn.ButtonPushedFcn = @(src, event) calculate_result('+');
    subtract_btn.ButtonPushedFcn = @(src, event) calculate_result('-');
    multiply_btn.ButtonPushedFcn = @(src, event) calculate_result('*');
    divide_btn.ButtonPushedFcn = @(src, event) calculate_result('/');
    
    function calculate_result(operation)
        num1 = num1_field.Value;
        num2 = num2_field.Value;
        
        switch operation
            case '+'
                result = num1 + num2;
            case '-'
                result = num1 - num2;
            case '*'
                result = num1 * num2;
            case '/'
                if num2 ~= 0
                    result = num1 / num2;
                else
                    result = NaN;
                    uialert(fig, 'Cannot divide by zero', 'Error');
                end
        end
        
        result_field.Value = result;
    end
end

Parallel Computing (Parallel Computing Toolbox)

% Start parallel pool
% parpool('local', 4);  % Start parallel pool with 4 workers

% Parallel processing with parfor
n = 1000000;
data = rand(n, 1);
results = zeros(n, 1);

% Regular for loop
tic;
for i = 1:n
    results(i) = sqrt(data(i)) + log(data(i) + 1);
end
serial_time = toc;

% Parallel for loop
tic;
parfor i = 1:n
    results(i) = sqrt(data(i)) + log(data(i) + 1);
end
parallel_time = toc;

fprintf('Serial processing time: %.4f seconds\n', serial_time);
fprintf('Parallel processing time: %.4f seconds\n', parallel_time);
fprintf('Speedup: %.2fx\n', serial_time/parallel_time);

% Close parallel pool
% delete(gcp('nocreate'));

Versions

Version Status Key Features Release Year
MATLAB R2024a Latest AI features enhancement, performance improvements 2024
MATLAB R2023b Current Live Editor improvements, App Designer features 2023
MATLAB R2023a Current New graphics features, numerical computing improvements 2023
MATLAB R2022b Current Functional programming features expansion 2022
MATLAB R2022a Current New data types and algorithms 2022
MATLAB R2021b Supported Performance improvements, new toolboxes 2021

Reference Pages

Official Documentation

Learning Resources

Specialized Toolboxes