MATLAB (Matrix Laboratory) is a high-performance programming language and computing environment widely used for mathematical computation, data analysis, algorithm development, and visualization. Its strength lies in matrix operations, making it particularly powerful for engineering and scientific applications.
Quick Tip: Always use the help command followed by a function name to get detailed information about any MATLAB function.
MATLAB code is executed in the Command Window or saved as script files (.m files). Statements typically end with a semicolon (;) to suppress output. Without a semicolon, MATLAB displays the result of the operation.
% This is a comment in MATLABdisp('Hello, World!'); % Displays the textvariable = 5 + 3 % Calculations without semicolon show outputresult = variable * 2; % Semicolon suppresses output MATLAB is case-sensitive, meaning 'variables' and 'Variables' would be treated as different identifiers. Comments start with the percent (%) symbol.
Variables in MATLAB don't require explicit declaration. They are created when assigned their first value. MATLAB supports various data types including numeric, character, logical, and cell arrays.
x = 10; % Integery = 3.1415; % Floating-pointz = 2 + 3i; % Complex number (real + imaginary*i)s = 'text'; % String (character array) | Operator | Description | Example |
|---|---|---|
| + | Addition | a + b |
| - | Subtraction | a - b |
| * | Multiplication | a * b |
| / | Division | a / b |
| .* | Element-wise multiplication | a .* b |
| ./ | Element-wise division | a ./ b |
| ^ | Matrix power | a ^ 2 |
| .^ | Element-wise power | a .^ 2 |
Warning: Pay attention to the difference between the dot (.) operator and the regular operator. The dot operator performs element-wise operations on arrays, while the regular operator performs matrix operations.
MATLAB provides standard control flow statements like loops, conditional statements, and switch cases.
if condition % code to execute if condition is trueelseif another_condition % code to execute if another_condition is trueelse % code if none of the above conditions are trueend for i = 1:n % code to execute n times disp(i);end while condition % code to execute while condition is true % be sure to include code that changes the condition!end switch expression case value1 % code if expression == value1 case value2 % code if expression == value2 otherwise % code if none of the cases matchend Matrices are the core data structure in MATLAB. They can be created directly using square brackets.
% Creating a row vectorv = [1, 2, 3];% Creating a column vectorw = [1; 2; 3];% Creating a 2x3 matrixA = [1, 2, 3; 4, 5, 6];% Creating a matrix using a rangeB = 1:5; % Creates [1 2 3 4 5]C = 0:2:10; % Creates [0 2 4 6 8 10]% Special matricesI = eye(3); % 3x3 identity matrixZ = zeros(3,4); % 3x4 matrix of zerosO = ones(2,5); % 2x5 matrix of onesR = rand(3); % 3x3 matrix of random numbers % Using parentheses to access elementsA(2,3) % Element in 2nd row, 3rd columnA(2,:) % 2nd row, all columnsA(:,3) % All rows, 3rd column% Using colon rangesA(1:2,2:3) % Submatrix with rows 1-2 and columns 2-3 | Operation | Description | Example |
|---|---|---|
A' | Transpose of A | A_transpose = A' |
inv(A) | Inverse of A | A_inv = inv(A) |
det(A) | Determinant of A | det = det(A) |
rank(A) | Rank of A | r = rank(A) |
eig(A) | Eigenvalues of A | eigenvalues = eig(A) |
MATLAB offers powerful tools for data visualization. Here are some essential plotting functions:
% Two-dimensional line plotx = linspace(0, 2*pi, 100);y = sin(x);plot(x, y, 'r-', 'LineWidth', 2);xlabel('x');ylabel('y');title('Sine Wave');grid on;legend('sin(x)'); | Function | Description | Example |
|---|---|---|
plot | 2D line plot | plot(x,y) |
scatter | Scatter plot | scatter(x,y) |
bar | Bar graph | bar(x,y) |
histogram | Histogram | histogram(data) |
pie | Pie chart | pie(data) |
surf | 3D surface plot | surf(Z) |
contour | Contour plot | contour(Z) |
Quick Tip: Use hold on to add multiple plots to the same figure and hold off to return to the default behavior.
Functions are reusable blocks of code that accept inputs and return outputs. In MATLAB, functions are saved in .m files with the same name as the function.
function [output1, output2] = myFunction(input1, input2) % Comments describing the function % Function body output1 = input1 + input2; output2 = input1 * input2;end % Defining an anonymous functionsquare = @(x) x.^2;result = square(5); % Returns 25 | Function | Description | Example |
|---|---|---|
max/min | Maximum/minimum value | m = max(A) |
mean | Average value | avg = mean(A) |
std | Standard deviation | s = std(A) |
sum | Sum of elements | s = sum(A) |
sort | Sort in ascending order | sorted = sort(A) |
find | Find indices of specific elements | indices = find(A > 5) |
size | Dimensions of array | s = size(A) |
length | Length of longest dimension | l = length(A) |
MATLAB provides various functions for handling input and output operations.
% Display outputdisp('This is a message');fprintf('The value is %d\n', variable); % Formatted output% Get user inputname = input('What is your name? ', 's');number = input('Enter a number: '); % Working with filessave('myData.mat'); % Save workspace to a fileload('myData.mat'); % Load from a file% Reading/writing text filesfileID = fopen('data.txt', 'w');fprintf(fileID, '%d %d\n', 10, 20);fclose(fileID);data = load('data.txt'); Warning: Always close files with fclose after opening them with fopen to prevent memory leaks and file access issues.
Effective debugging is essential for developing reliable code. Here are some key MATLAB debugging tools:
| Command | Description |
|---|---|
keyboard | Pause execution and give control to keyboard |
dbstop | Set breakpoints |
dbcont | Continue execution |
dbstep | Step to next line |
dbquit | Exit debug mode |
% Try-catch block for error handlingtry % Code that might generate an error result = compute_something();catch ME % Error handling code disp(['Error occurred: ', ME.message]);end
