Basic MATLAB Syntax
| Concept | Example | Description |
|---|---|---|
| Comments | % This is a comment | Anything after % is ignored by MATLAB |
| Assignment | x = 5; | Assigns the value 5 to variable (x) |
| Suppress Output | x = 5; | The semicolon (;) hides the output |
| Display Output | x = 5 | Without (;), MATLAB displays the result |
| Vectors | v = [1 2 3 4] | Row vector v = [1; 2; 3; 4]; (column vector) |
| Matrices | A = [1 2; 3 4] | 2 x 2 matrix. Rows separated by (;) |
| Element Access | A(2,1) | Access element in row 2, column 1. |
| Range (colon) | 1;5 -> [1 2 3 4 5] | Creates an arithmetic sequence. 1:2:9 -> [1 3 5 7 9] |
Mathematical Operations
| Operation | Syntax | Example |
|---|---|---|
| Addition/Subtraction | +/- | a + b, a - b |
| Multiplication | * | A*B (matrix multiplication) |
| Element-wise Multiplication | .* | A.*B (multiply element by element) |
| Division | /,.\ | A/B (right division), A.\B (element-wise left division) |
| Power | ^ or .^ | A^2 (matrix power), A.^2 (element-wise power) |
| Transpose | ' | A' (matrix transpose) |
| Built-in functions | sin(x), cos(x), exp(x), log(x), sqrt(x) | Common math functions. |
| Constants | pi, inf, nan, eps | Ï€, ∞, NaN, smallest increment. |
Plotting and Visualization
| Operation | Syntax | Example |
|---|---|---|
| plot(x,y) | 2D plot | x=0:0.1:2*pi; plot(x, sin(x)); |
| xlabel('text') | Axis labels | xlabel('Time'); ylabel('Amplitude'); |
| title('text') | Plot title | title('Sine Wave'); |
| legend('A','B') | Add legend | -- |
| grid on | Add grid | -- |
| figure | Open new figure window | -- |
| subplot(m,n,p) | Multiple plots in one figure | subplot(2,1,1); plot(x,sin(x)); |
| -- | -- | -- |
Programming Structures
With structure "if statement", with syntax "matlab,
if x > 0
elseif x < 0
disp('Negative')
else
disp('Zero')
end
Tags
Teaching Materials