MATLAB onramp

load / save : all variables to a file load filename x -> loads x variable from the file to current context

end a line with semicolon (;) to prevent output to be shown in the output pane

every computation result is stored in ans variable

clear: removes all variables

everything is an array in MATLAB scalars are 1x1 arrays x = [3 4 5] is a row vector (1x3) x = [3; 4; 5] is a column vector (3x1)

how to create row vectors with evenly spaced elements x = start:spacing:end example: x = 1:2:9 gives x = [1 3 5 7 9]


linspace(start, end, #ofelements) -> row vector

how to create column vector from row vector? transpose: x = x’

how to create a matrix with random values, all zeros, all ones: rand(m, n) zeros(m, n) ones(m, n)

size(matrix) gives the size of a matrix as row vector that is of the form [#rows #columns]


INDEXING: matrix(i, j) where i is the row index and j is the column index

can also specify ranges using : like x(2:3)

end keyword can be used in indexing

when a single index is given to a matrix like x(idx) then matlab traverses column-by-column till idx is reached

05/03/2025

volumes = data(:, end-1:end) selscts the last two colums of data

for non consecutive indices use data([1 3 7])


Operations on arrays

+ adds a number to all elements of array + also adds two same sized arrays / divides each element of an array by a number max(vector), round(vector), sqrt(vector) perform element wise operation

* preforms matrix multiplication .* performs dot product

[1 2; 3 4; 5 6; 7 8] .* [1;2;3;4] is completely valid and gives dot product of both column vectors of array 1 with vector 2. result is: 1 2 6 8 15 18 28 32


Destructuring

[rows, columns] = size(matrix) creates 2 variables to store the two sizes

max() also returns two values when destructured like above, first one being the max value and second one being the index

if first variable needs to be ignored use ~ as [~, cols] = fn(vector)


randi([imin, imax], #rows, #cols) creates an array of specified size with values from uniformly distributed random integers between imin and imax


Plot

plot(x, y) plots same sized vectors also takes an optional third argument as a string defining formatting (color of line (r,g,b,c,m,y,k,w), line style (-,—,:,-.), marker shape (.,*,x,o,+,_,|))

hold on the next plot functions are drawn on the same graph

hold off continue in the default mode (separate graphs for each plot function)

plot(vector_x) plots the vector elements on the y axis with x axis having numbers 1 to n

other options like plot(x, y, “ro-”, LineWidth=4)

histogram(vector, FaceColor=“y”) plots a histogram in yellow color


Plot Annotations

title(“Plot title”) xlabel() and ylabel() for labelling the axes legend(“item1”, “item2”, “item3”, …) describe the plots in order of creation.

numbers can be joined in text using + operator


Importing

use the import tool the name of variable is the same as the filename access columns by filename.column_header

slicing also works here. generates a new table.


Relational operations

produce a logical output 1 (true) or 0 (false)

array also support logical operations, result is a new same-sized array with operation performed on each element example [1 2 3 4] < 3 gives [1 1 0 0]

Logical Indexing

we can use a logical array as an index. result is the original array but filtered accordingly example v1(v1 < 4) extracts all the elements of v1 that are less than 4

the arrays need not be the same

assignment can also be done as x(x==999) = 1


Decision branching
if-elseif-else

if condition block of code elseif condition2 block of code else block of code end

for loops

for loop_counter = vector block of code end


Summary

Summary of MATLAB Onramp

Basic Syntax

ExampleDescription
x = piCreate variables and assign values with the equal sign (=).
The left side (x) is the variable name, and the right side (pi) is its value.
y = sin(-5)Provide inputs to a function using parentheses.

Desktop Management

FunctionExampleDescription
savesave data.matSave your current workspace to a MAT-file.
loadload data.matLoad the variables in a MAT-file to the workspace.
clearclearClear all variables from the workspace.
clcclcClear all text from the Command Window.
formatformat longChange how numeric output appears in the Command Window.

Array Types

ExampleDescription
4scalar
[3 5]row vector
[1;3]column vector
[3 4 5; 6 7 8]matrix

Evenly Spaced Vectors

ExampleDescription
1:4Create a vector from 1 to 4, spaced by 1, using the colon operator (:).
1:0.5:4Create a vector from 1 to 4, spaced by 0.5.
linspace(1,10,5)Create a vector with 5 elements. The values are evenly spaced from 1 to 10.

Matrix Creation

ExampleDescription
rand(2)Create a square matrix with 2 rows and 2 columns.
zeros(2,3)Create a rectangular matrix with 2 rows and 3 columns of 0s.
ones(2,3)Create a rectangular matrix with 2 rows and 3 columns of 1s.

Array Indexing

ExampleDescription
A(end,2)Access the element in the second column of the last row.
A(2,:)Access the entire second row.
A(1:3,:)Access all columns of the first three rows.
A(2) = 11Change the value of the second element of an array to 11.

Array Operations

ExampleDescription
[1 2; 3 4] + 1
ans =
2 3
4 5
Perform array addition.
[1 1; 1 1]*[2 2; 2 2]
ans =
4 4
4 4
Perform matrix multiplication.
[1 1; 1 1].*[2 2; 2 2]
ans =
2 2
2 2
Perform element-wise multiplication.

Multiple Outputs

ExampleDescription
[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

ExampleDescription
doc randiOpen the documentation page for the randi function.

Plots

ExampleDescription
plot(x,y,“ro—“,LineWidth=5)Plot a red (r) dashed (—) line with a
circle (o) marker, with a heavy line width.
hold onAdd the next line to the existing plot.
hold offCreate new axes for the next plotted line.
title(“My Title”)Add a title to a plot.
xlabel(“x”)
ylabel(“y”)
Add labels to axes.
legend(“a”,“b”,“c”)Add a legend to a plot.

Tables

ExampleDescription
data.HeightYardsExtract the variable HeightYards from the table data.
data.HeightMeters = data.HeightYards*0.9144Derive a table variable from existing data.

Logical Indexing

ExampleDescription
[5 10 15] > 12Compare the elements of a vector to the value 12.
v1(v1 > 6)Extract all elements of v1 that are greater than 6.
x(x==999) = 1Replace all values in x that are equal to 999 with the value 1.

Programming

ExampleDescription
if x > 0.5
y = 3
else
y = 4
end
If x is greater than 0.5, set y to 3.

Otherwise, set y to 4.
for c = 1:3
disp(c)
end
The loop counter (c) progresses through the
values 1:3 (1, 2, and 3).

The loop body displays each value of c.