Summary of MATLAB Onramp: Basic Syntax
Summary of MATLAB Onramp: Basic Syntax
Basic syntax
Example Description
x = pi Create variables with the equal sign (=).
The left-side (x) is the variable name containing the value on the right-side (pi).
y = sin(- You can provide inputs to a function using parentheses.
5)
Desktop management
Functio
n Example Description
save save data.mat Save your current workspace to a MAT-file.
load load data.mat Load the variables in a MAT-file to the Workspace.
Array types
Example Description
4 scalar
[3 5] row vector
[1;3] column vector
[3 4 5;6 7 8 matrix
]
Evenly-spaced vectors
Example Description
1:4 Create a vector from 1 to 4, spaced by 1, using the colon (:) operator.
Creating matrices
Example Description
rand(2) Create a square matrix with 2 rows and 2 columns.
Indexing
Example Description
A(end,2) Access the element in the second column of the last row.
Array operations
Example Description
[1 1; 1 1]*[2 2;2 2] Perform matrix multiplication.
ans =
4 4
4 4
[1 1; 1 1].*[2 2;2 Perform element-wise multiplication.
2]
ans =
2 2
2 2
Multiple outputs
Example Description
[xrow,xcol] = size(x Save the number of rows and columns in x to two different variables.
)
[xMax,idx] = max(x) Calculate the maximum value of x and its corresponding index value.
Documentation
Example Description
doc rand Open the documentation page for the randi function.
i
Plotting
Example Description
plot(x,y,"ro-","LineWidth",5 Plot a red (r) dashed (--) line with a
) circle (o) marker, with a heavy line width.
Using tables
Example Description
data.HeightYards Extract the variable HeightYards from
the table data.
data.HeightMeters = data.HeightYards*0.914 Derive a table variable from existing data.
4
Logicals
Example Description
[5 10 15] > 1 Compare a vector to the value 12.
2
Programming
Example Description
if x > 0.5 If x is greater than 0.5, set the value of y to 3.
y = 3
else Otherwise, set the value of y to 4.
y = 4
end