Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

MATLAB QUICK GUIDE

0. General
Semi-colons are used to suppress the output to the command window, if you don’t wish the output of a line of script to
appear in the command window place a semi-colon at the end of the line.
MATLAB is case sensitive, it is easier to keep all variable and function names lower-case. Make sure when you save m
files they are in lower case too. We use uppercases for global variables.
MATLAB is fairly forgiving when adding spaces to your code, however ensure there is no space between a function
name and the brackets containing the input arguments.
In the below examples the >> is used to specify that this is an inputted line of code, rather than an output.
clc clears the command window.
clear clears the workspace.

1. Scalars, vectors and Matrices 2. Indexing vectors and Matrices


1.1 Creating a scalar: 2.1 Indexing a value in a vector:
>> x = 23 y = [3 5 7 9 11 13]
x = 23 >> x = y(4) indexes the value in y at index 4.
or x = rand will create a random number between 0 and x = 9
1. >> x = y([1 4 5]) indexes the values in y and
x = randi(imax) will create a random integer between indices 1, 4 and 5.
While loops
0 and imax. x = 3 9 11
1.2 Creating a row vector: >> x = y(2:5) indexes the values in y at indices 2
>> y = [1, 9, 4] or >> y = [1 9 4] to 5.
y = 1 9 4 x = 5 7 9 11
If elseif else
Colon operator can be used to create vectors: >> x = y([1 3 5; 2 4 6]) will create a matrix
>> y = 1:4 will create a row vector equally spaced by a using the values at odd indices for the first row and
increment of 1 from 1 to 4. those at the even indices for the second row.
y = 1 2Switch3 4 x = 3 7 11
>> y = 2:3:12 will create a row vector that starts at 2 5 9 13
and will increase in increments of 3 until it reaches 12. >> x = y(1:2:end)will return the value at index 1
y = 2 5File I/O
8 11 then every other value up to the end, the middle value
>> y = linspace(1, 4, 7) function create an equally being the increment.
spaced vector of 7 values, starting at 1 and ending at 4. x = 3 7 11
y = 1.00 1.50functions
Useful 2.00 2.50 3.00 3.50 4.00 2.2 Indexing a value in a matrix:
1.3 Creating a column vector: Using two indexes you provide the row and the column,
>> y = [1 using a single index MATLAB counts down each
9 column in turn e.g.
Plotting z = 2 4 4 3
4] or y = [1; 9; 4] or y = [1, 9, 4]’
y = 1 2D plots 0 1 0 2
9 1 5 4 5
4 3D plots >> x = z(3,2) or >> x = z(6)
1.4 Creating a matrix: x = 5
Other plotting functions
>> z = [2, 4, 4, 3; 0, 1, 0, 2; 1, 5, 4, 5] The colon operator can be used to get ‘all values’ e.g.
or >> y = z(:,3) will return all the row values in
>> z = [2 4 4 3; 0 1 0 2; 1 5 4 5] or column 3.
>> z = Functions
[2 4 4 3 y = 4
0 1 0 2 0
1 5 4 5] 4
gives: >> y = z(2, :) will return all the column values in
z = row 2.
2 4 4 3 y = 0 1 0 2
0 1 0 2 >> y = z(3, 2:end) will return the values in row 3
1 5 4 5 from column 2 to the last column (in this case 4).
or to create pre-populated matrices: y = 5 4 5
>> z = zeros(m,n) will create an mxn matrix of zeros. >> x = z(end) will return the last value in a matrix.
>> z = rand(m,n) will create an mxn matrix of random x = 5
numbers between 0 and 1. To get more than one scattered values we need to use
>> z = randi(imax,m,n) will create an mxn matrix of the single index value e.g.
random integers between 0 and imax. >> y = z([1 3 4 11])
y = 2 1 4 2

MECH1010 - Computers in Engineering Analysis - MATLAB Quick Guide Page | 1


2. Indexing vectors and Matrices 3. Useful functions:
2.3 Replacing a value in a vector: x = sum(y) sums the values in vector y or if y is a matrix
y = [3 5 7 9 11 13] will sum the values in each column.
>> y(4) = 1 replaces the value in y at index 4 with x = abs(y) returns the absolute value of y.
1. x = sign(y) will create a random number
y = 3 5 7 1 11 13 [maximum, ind] = max(y) will return the maximum
>> y([1 3 5]) = [2 4 6] replaces the values at value of y and the index. If y is a matrix it will return the
indices 1, 3 and 5 with 2, 4 and 6 respectively. maximum value in each column.
y = 2 5 4 9 6 13 [minimum, ind] = min(y) will return the minimum
>> y([1 3 5]) = 6 replaces the values at indices value of y and the index. If y is a matrix it will return the
1, 3 and 5 with 6. minimum value in each column.
y = 6 5 6 9 6 13 sin(y) tan(y) cos(y) trigonometric fcns in radians.
>> y(3) = [] will remove the value in y at index 3. asin(y) atan(y) acos(y) inverse trig fcns in radians.
y = 3 5 9 11 13 sind(y) cosd(y) tand(y) trig fcn in degrees.
>> y(1:3)= [1 2 3] will replace the values in y at x = sqrt(y) returns the square root of y.
indices 1 to 3 with the values 1, 2 and 3. x = nthroot(y,n) returns the real nth root of y.
y = 1 2 3 9 11 13
pause pauses until the user presses a key.
2.4 Replacing a value in a matrix:
x = size(y) returns a vector containing the number of
Using two indexes you provide the row and the column,
rows and columns in y.
using a single index MATLAB counts down each
x = length(y) returns the length or y if a vector of the
column in turn e.g.
z = 2 4 4 3 greatest dimension of a matrix.
0 1 0 2 x = exp(y) returns the exponential of y.
1 5 4 5 x = ceil(y) rounds y up to the next integer.
>> z(3,2)=0 or >> z(8) = 9 x = floor(y) rounds y down to the next integer.
z = 2 4 4 3 z = 2 4 4 3 x = fix(y) rounds in the direction of zero.
0 1 0 3 0 1 9 3
1 0 4 5 1 5 4 5 4. Conditional logic
or we can replace a subset of the matrix: 4.1 Relational operators
>> z(1:3,2) = [1;2;3]
x == y returns a true if x is equal to y.
z = 2 1 4 3
x ~= y returns a true if x is not equal to y.
0 2 0 2
1 3 4 5 x > y returns true if x is greater than y.
or scattered values using linear indexing, you can’t x < y returns true if x is less than y.
index scattered values using row/column indexing. x >= y returns true if x is greater than or equal to y.
>> z([2,6,10]) = 9 x <= y returns true if x is less than or equal to y.
z = 2 1 4 9 x = 5 6 7 2
9 2 0 2 y = 5 2 5 4
1 9 4 5 >> z = x == y
>> z(2,5) = 4 will increase the size of the matrix z z = 1 0 0 0
and leave extra values as zero, this will return an error >> z = x >= y
if you try to do this with linear indexing. z = 1 1 1 0
z = 2 4 4 3 0 4.2 Logical operators
0 1 0 2 4 x & y returns true is x and y are non-zero. x and y can be
1 5 4 5 0 scalar or vectors or matrices of the same size.
Remember the apostrophe can be used to transpose x && y returns true if x and y are non-zero. x and y are
matrices: scalars only. y not evaluated if x is zero.
>> z = z ' x | y returns true if x or y are non-zero. x and y can be
z = 2 0 1 scalar or vectors or matrices of the same size.
4 1 5 x || y returns true if x or y are non-zero. x and y are
4 0 4 scalars only. y not evaluated if x is non-zero.
3 2 5 x = 5 0 0 2
And we can add vectors or other matrices to our y = 5 2 0 0
existing matrices: >> z = x & y
>> z(:,5:8) = z or >> z = [z,z] z = 1 0 0 0
z = 2 4 4 3 2 4 4 3 >> z = x | y
0 1 0 2 0 1 0 2 z = 1 1 0 1
1 5 4 5 1 5 4 5 >> z = ~x
z = 0 1 1 0

MECH1010 - Computers in Engineering Analysis - MATLAB Quick Guide Page | 2


5. Switch/case structures: 8. If/Else and If/Elseif/Else
switch switch_variable if conditional_expression
case value_of_switch_variable [code here]
[code here] elseif conditional_expression
case another_value_of_switch_variable [code here]
[code here] else
otherwise [code here]
[default code here] end
end The Conditional_expression uses relational and logical
Switch_variable is a variable containing either a scalar operators. If the if conditional_expression is true, the
numeric or a string. Each case will run depending on the code below it runs and execution jumps to end. If the if
value of switch_variable, if there is not a case for a conditional_expression is not true and elseif
particular value, the otherwise case will run. Any number conditional_expression is true, the code below elseif
of cases can be included and the otherwise case is statement runs and execution jumps to end. If none of
optional. above conditional_expressions are true, the else case
6. Find function: will execute.
If z is a vector: x=find(conditional_expression of Note no conditional_expression associated with else
z) will return the indexes of all values of z that satisfy the case. This is default case. All but the if statement and
conditional expression. e.g. end statements are optional. Only one else case may
>> z = [45 5 6 27 81 9 54] exist and only one if case.
>> x = find(z > 20 & z < 70) e.g.
x = 1 4 7 >> x = 6 >> x = 6 >> x = 6
If z is a matrix: x=find(conditional_expression of y) >> y = 15 >> y = 10 >> y = 6
then x will be the linear index values of y that satisfy the >> z = 10 >> z = 10 >> z = 10
if (x > y) | | (z == y)
conditional expression. e.g.
result = 1;
>> z = [45 5 6 27 81 9 54;
elseif (x == y) & (y <= z)
25 7 18 32 5 6 8]
result = 2;
>> x = find(z > 20 & z < 70)
else
x = 1
result = 3;
2
end
7
result = 3 result = 1 result = 2
8
13
[r,c]=find(conditional_expression of y) will 9. For Loops
return two column vectors, one containing the row indices for x = vector or matrix
and one containing the column indices of the values in z [loop code]
end
that satisfy the conditional expression. e.g.
>> [r,c] = find(z > 20 & z < 70) A for loop run the number of times equal to the length of
r = 1 the row vector or the number of columns in a matrix.
2 Each time the loop iterates x will take on a new value in
1 the vector or column in the matrix. y = [4 6 3];
2 for x = y
1 x % Display x
c = 1 end
1 The loop will run three times, x is displayed:
4 x = 4
4 x = 6
7 x = 3
If y is a column vector y = [4; 6; 3]
7. While Loops for x = y
while conditional_expression x’ % Display x
[loop code] end
end The loop will run once taking the column, x is displayed:
While loop will keep iterating the loop code each time x = 4
while the conditional expression is true. As soon as the 6
3
conditional expression becomes false, the loop ceases to
for index = 1:3
iterate and we exit the loop.
index % Display x
x = 1
end
while x < 3
x = x+1; Loop will run 3 times.
end index = 1
index = 2
This will run until x is equal to 3, then the loop will stop.
index = 3

MECH1010 - Computers in Engineering Analysis - MATLAB Quick Guide Page | 3


For Loops continued… 10. Plotting functions
When the value we are passing to the for loop is a matrix 10.2 3D plots
we take a column at a time. plot3(x,y,z) will plot z against x and y in a figure
y = [1 2 3; 4 5 6; 7 8 9] window, x, y and z must be vectors of the same length.
for x = y plot3(x, y, z, ‘c’, p, q, r,‘g--‘) will plot z
x % display x
against x and y as a cyan solid line and r against p and q
end
as a green dot dashed line. x, y and z and p, q and r must
will run 3 times, each time taking a new column of y.
x = 1 be vectors of the same length.
4 zlabel(‘string’) adds a label, string to the z axis.
7 The following plots plot Z values for combinations of x
x = 2 and y values. Z will be a matrix with the number of
5 columns equalling the length of vector x and rows
8
equalling the length of vector y.
x = 3
surf(x, y, Z) creates a surface plot of the data
6
9
We can nest for loops to access the values in the columns.
for x = y
for z = y’ % transpose y
z % Display z
end
end
Inner loop will run 3 times for every iteration of the outer
loop which will run three times.
z = 1
z = 4 mesh(x, y, Z) creates a mesh plot of the data
z = 7
z = 2
z = 5
z = 8
z = 3
z = 6
z = 9

10. Plotting functions


10.1 2D plots
plot(x,y) will plot y against of x in a figure window, x contour(x, y, Z) creates a 2D plot of the 3D data
and y must be vectors of the same length. showing contours of edges of the same potential.
plot(x, y, ‘r:’, t, z, ‘b--‘) will plot y against x
as a red dotted line and z against t as a blue dashed line. x
and y and t and z must be vectors of the same length.
hold on will hold the current figure axes allowing further
plot functions to appear on the same plot.
hold off with release the axes.
figure(1) will open a new figure window , figure 1 if pcolor(x, y, Z) create a solid colour 2D plot of 3D
already open it makes it the current figure on which data.
plotting functions will apply.
xlabel(‘string’) adds a label, string, to the x axis.
ylabel(‘string’) adds a label, string, to the y axis.
title(‘string’) adds a title above the plot axes.
legend(‘string1’, ‘string2’) adds a legend with
each string assigned to a different line.
grid on / off will turn on or off the grid. colormap can be used to change the colour
axes equal sets the scaling on the axes to the same appearance, e.g. colormap Autumn or colormap Hot
scale. shading can change the appearance of surface plots
axes([xmin, xmax, ymin, ymax]) sets the range of e.g. shading flat, shading faceted or
the axes. shading interp
subplot(m,n,r) will place mxn subplots in a figure colorbar add a colour bar showing the Z axis colour
window with r representing the currently active axes. key as shown in the pcolor plot above.

3D Plots MECH1010 - Computers in Engineering Analysis - MATLAB Quick Guide Page | 4


x & y returns true is x and y are non-zero. x and y can
11. File I/O functions 12. User interactions functions:
11.1 Load / Save 12.1 Input
load filename.mat can be used to load .mat files into x = input(‘string’) will display the string in the
the workspace. command window. Awaits user input in the command
save filename.mat will save the current workspace to window after displaying the string. User should type a
the filename numeric and this will be assigned the the variable x.
11.2 CSVREAD and CSVWRITE x = input(‘sting’, ‘s’) will do the same,
csvread allows us to read from a comma separated value however the value x will be a string rather than a
file. The first input argument is the filename, The next numeric.
optional input arguments are the row and column of 12.2 Disp
where to start reading, R and C. Further input argument disp() will display whatever the input argument is. e.g.
is the range of the data read using R1, C1, R2 and C2. >> x = 4;
csvread('data.csv', R, C, [R1, C1, R2, C2]) >> disp(x)
All except the filename are optional. Will display: 4
csvwrite allows us to write a variable, M, to a filename >> disp(‘Put this in the command window’)
starting at row R and column C. Will display: Put this in the command window
csvwrite('data.csv', M, R, C) >> disp([‘Put the value x in the command
R, C, R1, C1, R2, C2 are zero-indexed. window: ‘ num2str(x)])
11.3 DLMREAD and DLMWRITE Will display: Put the value x in the command
dlmread allows us to read from a file with a defined window: 4
delimiter. The first input argument is the filename, the 12.3 Menu
second is the delimiter, most common will be ‘\t’, ‘,’ and ‘ >> choice = menu(‘menutitle’, ‘option1’,
‘. That is a tab, comma or space. The next input ‘option2’) will open a dialog box with the string
arguments are the row and column of where to start menutitle at the top with buttons for option1 and option2.
reading: If option1 is pressed choice will be 1 and if option2 is
dlmread(‘data.txt’, ‘,’, R, C)
pressed choice will be 2.
The R and C values can be replaced by the range
12.4 Fprintf and Sprintf
argument to specify the start and end of the data to be
fprintf is used to either display to the Command Window
recorded.
or write to file. See File I/O section for latter.
dlmread(‘data.txt’, ‘\t’, [R1, C1, R2, C2])
fprintf(‘string including placeholders
dlmwrite allows us to write to a file with a defined
%’, variables) will display the string in the
delimiter. The first argument is the filename, the second
Command Window placing values in variables one place
is the variable containing the data to write to file. An
holder at a time. A placeholder is set by a percentage
optional third input argument allows us to append to the
sign followed by the type field (see below). If passed a
end of the file, further argument is the delimiter. R and C
matrix, fprintf will go through each column in turn,
specify the row and column of where to start writing.
dlmwrite(‘data.txt’, M, ‘\t’ R, C) or printing out the string until all values have been
dlmwrite(‘data.txt’, M, ‘-append’, ‘ ‘) displayed. E.g.
R, C, R1, C1, R2, C2 are zero-indexed. table = 2 4 6
4 16 36
11.4 Other File Functions:
>> fprintf(‘%d squared is %5.2f\n’, table)
imread(‘filename’) reads an image file 2 squared is 4.00
imwrite(A, ‘filename’) write the image data A to 3 squared is 9.00
file. 4 squared is 16.00
filename = uigetfile(‘filter spec’, Note because 5 is used for the width of the fixed point
‘Dialog title’) Opens a dialog window the the title value, the lines of text are nicely formatted
specified by the second argument. filter spec is used to sprintf works the same except the output is a string
filter files, for example ‘*.csv’ will just show csv files in the variable.
dialog window. Type field formats for sprint and fprintf
FileID = fopen(‘filename’, ‘permission’) %f fixed point, displays 6 values after decimal point,
will open the file specified by filename for the permission %a.bf fixed point (6.2f signifies minimum width of 6
given. ‘wt’ would be for writing to a text file. ‘rt’ would be figures can be used, 2 after decimal place.
for reading from a text file. %e exponential notation
fclose(FileID) closes the file open specified by %d decimal (integer) notation, i.e. 10
FileID. %c characters (one character at a time)
fprintf(FileID, ‘string including %s string of characters (all at once)
placeholders %’, variables) will write to the Special format commands
\n linefeed
file specified by FileID the string placing the values
\r carriage return
in variables in the placeholders. See user input
\t tab
output section for more details.
MECH1010 - Computers in Engineering Analysis - MATLAB Quick Guide Page | 5

You might also like