01 Matlab Basics1 2019
01 Matlab Basics1 2019
MATLAB basics
1
1. MATLAB/OCTAVE BASICS
During the next practices, various engineering problems will be solved with numerical
methods algorithms using the Matlab mathematical environment. Matlab software is
available for the students of Budapest University of Technology and Economics
(BUTE) for educational purposes from March 2017. A good alternative might be the
Octave mathematical environment, which is a free, open-source program where you
can use essentially the same commands as in Matlab. Even the graphical interface is
very similar in the two programs, with optional rearrangeable windows (see Figures 1,
2). Octave can be downloaded from https://www.gnu.org/software/octave/, the current
version is 5.1.0, which came out on Mar 1, 2019.
The students can create a MathWorks account on the Matlab site using BME email
address, using this account they can access Online Matlab also. With the MathWorks
account, students can practice the basics of Matlab solving the tasks of the Matlab
Onramp online study site, which is recommended for everyone (it takes about 2-3
hours). There are other good online practice options at Matlab Cody site.
1 Refernce for Matlab/Octave Basics: Todd Young and Martin J. Mohlenkamp: Introduction to
Numerical Methods and Matlab Programming for Engineers, Department of Mathematics, Ohio Univer-
sity, July 24, 2018, http://www.ohiouniversityfaculty.com/youngt/IntNumMeth/book.pdf
STARTING MATLAB/OCTAVE
The most important parts of the graphical interface are the current folder where the
current directory is stored, the command window, the workspace with the used
variables, the command history with all the used commands and the editor ( editor).
Left-click and hold on the name of a panel to drag and drop them into the blue-colored
area. You may want to dock the editor by clicking on the arrow at the top right of the
Editor window.
Keep in mind that file names used in Matlab should not begin with a number or contain
special characters or spaces! In the program, only those functions and files can be
used or run which are in the current directory.
HELP, DOCUMENTATION
We can learn a lot from the proper use of documentation. In older Matlab versions
(before 2019), typing help to the Command Window listed the categories of various
built-in functions. Here you could either double-click on the category name or type in
the name of the category after the help command (in this handbook, the > sign
indicates the Matlab commands). From Matlab R2019a, typing only the ’help’
command will display help of the last used command. Try the next:
help elfun
This will list the 'Elementary math functions', e.g. trigonometric, exponential, complex
and rounding functions. If we know the name of a function, we can type it after help:
help 'function name'
This gives you a description of the command and how to use it. E.g. try:
help rand
This command describes that the rand function generates an evenly distributed
random number between 0 and 1, specifies how to use it to call with one or more inputs,
and lists some associated commands (e.g. randn, which generates standard normal
random numbers with 0 expected values and 1 standard deviation).
The doc command works much like help, but is a much more detailed description of
the command, with many examples.
doc randn
Let's try the pwd function! Use the help command to figure out what the command
does!
Another useful function is the lookfor command. This can be used to search for a word
in the name of the command or in its description. Let's try the following:
lookfor rand
This will list all the commands whose names or their short description contains the
word rand. If the search takes too long, it can be aborted by pressing CTRL + C.
ONLINE DOCUMENTATION
The ’Tab’ button is very useful. If we do not know exactly the name of a particular
command, just the beginning, let’s start typing the beginning to the command line e.g.
pref, then press ’Tab’. If there is only one command with pref beginning, the ’Tab’
button will complete the command, if there are more, the ’Tab’ will list them. In this
case, there are several commands with the beginning of pref, e.g. prefdir (the name
of the directory where all settings, history, etc. are located) or preferences, which
opens the settings window.
The up and down arrow buttons are also very useful in the command line. With them,
the previous commands can be retrieved, executed and modified. Previous commands
can also be executed using the command history by double-clicking on the command
name.
TAB - use it to finish the started function/variable etc. name
ARROW KEYS - you can scroll around the previously processed commands (you can
access those from the command history too)
CTRL+ENTER - run the whole section
F9 - run the selected part
F5 - run the whole script
%% Entering numbers
a = 0.01
b = 1e-2
c = 1d-2;
a+c
clear a % deletes the variable 'a'
clear % (or 'clear all') clears all variables
pi % built-in value (3.14)
e = exp(1) % e^1 = e = 2.71
b = e^-10 % exponentiation
Basic formatting:
format long % 14 decimal digits
e, b
format short % 4 decimal digits
e, b
The basic variable type in Matlab is the matrix. Vectors are special matrices, 1xn row
vectors or mx1 column vectors. Square brackets are used in Matlab to define a matrix
or vector. If you work with matrices/vectors, be careful with the different parenthesis,
because each type is doing different operations: ( ), [ ], { } ! The elements are separated
by a comma or space within the row, and the rows are separated by semicolon.
z = [1 3 45 33 78] % rowvector
z = [1,3,45,33,78] % rowvector
t = [2; 4; 22; 66; 21] % column vectors
M = [1,2,3; 4,5,6] % matix, with 2x3 size
When displaying a vector, it can be problematic to have very small and very large
numbers at the same time. Let's look at the following vector, for example
x = [25 56.31156 255.52675 9876899999];
format short
x
The result is difficult to read and not very informative:
x = 1.0e+09 *
So far, we have been working from the command line, but solving a more complex
calculation would be very difficult using only the command window. Therefore it may
be better to collect the necessary commands/functions into a script file. The default file
type for Matlab is the * .m file, a simple text file that can be edited with any text editor.
In addition, in recent versions of Matlab, you can use the LiveScript file type (* .mlx),
in which you can mix Matlab instructions and formatted text, images, and see the
results right away. The disadvantage of this format is that this is Matlab's own format,
which can only be opened within Matlab.
You can run the script files by typing their names or just pressing F5, this will save and
run the program right away. Make sure that the filename does not start with a number
or contain spaces or special characters! Filenames must start with a letter and contain
only the English alphabet, numbers, and underscores (_).
If you don't want to run the whole program, you can write a return command
somewhere, and after pressing F5 the program will only run until that point.
Alternatively, pressing F9 will run only the selected part. You can divide the file into
sections using double % characters (%%) followed by a section title. You can execute
commands in a particular section by pressing CTRL+Enter. Let's start a new script file
by clicking on the plus sign (new) in the upper left corner and this will open a blank
page in the Editor. Save it to your current directory as practice1.m file!
The next table contains the data of a stress-strain diagram (σ-ε) of a steel bar for
reinforced concrete:
ε [%] 0 0.2 2 20 25
Useful specifiers:
Each figure and also the plotted elements can be named with a handle (an identifier).
You can use this to access any figure/element later if you want to set a property or
clear them. If you don't do further settings, by plotting a new element, the previous one
will be deleted.
clf % clear figure
f1 = figure; % the figure function creates a new figure
p1 = plot(x,y,'r*');
hold on % you can fix the diagram, to add new elements to it without
cleaning it first
p2 = plot(x,y);
p3 = plot(x,y,'bo');
delete(p1) % you can delete elements by using its handle
figure(1) % by referring to the number of the figure, you can work
on any previous figure
close % close figure
FUNCTIONS
There are many mathematical and other built-in functions in Matlab, it is useful to
browse the documentation to get to know them. Let's look at some of the basic math
functions, from ’Elementary math functions’ in the documentation, using the ’help
elfun’ command! The input variables of the functions are always enclosed in round
brackets. The default angular unit for trigonometric functions is radian.
sin(pi) % its value is 0 within the accuracy of the numerical
representation
cos(pi) % -1
tan(pi) % a large number instead of infinite
log(100) % natural logarithm
log10(100) % 10 based logarithm
3^4 % értéke: 81
sqrt(81) % 9
abs(-6) % 6
exp(0)
exp(0) is e0, its value is of course 1. The built-in functions work not only on numbers
but also on vectors.
x = linspace(0,2*pi,40)
y = sin(x)
figure(1); plot(x,y)
For more settings see help plot!
There are many ways to specify your own functions in Matlab, in simple cases we use
the so-called anonymous function, which is not saved as a separate program, only
assigned to a variable. Let’s define cos(2x) function in this way!
f = @(x) cos(2*x)
Here, after the @ symbol, you must specify the independent variables of the function,
and after a space you can write the formula. Let's plot this function also next to the sine
function you have just drawn. When drawing the sine function, we first calculated some
points of the function and plotted them using the plot command. We can plot functions
without calculating their points beforehand, using symbolic fplot or ezplot commands.
(Note: In Octave and older Matlab versions you can use only the ezplot command, in
newer Matlab fplot is recommended).
hold on
fplot(f,[0,2*pi]) % or ezplot(f,[0,2*pi])
Without the hold on command, the previously drawn elements will be deleted from the
figure, the hold off command restores this default mode. For fplot, you can specify an
interval where you want to display the function (it is optional, there is a default interval
also).
Calculate the squares of the integers between 1-10 using your own function! First, let’s
define a function to calculate the square of any number!
f1 = @(x) x^2
Matlab's default file type is a text file with the *.m extension. There are two main types,
script file and function. We have used the former in our work so far, now let's see the
differences between functions and script files!
One of the advantages of writing the functions into a separate file compared with the
anonymous functions is that it can be invoked from any other script file also. Another
advantage is that it can be used to perform more complex calculations, it is easy to
parameterize the input and output variables and a description can be added for help.
Let’s rewrite the previous square function into a separate function file! Click the plus
sign (new) in the upper left corner and a blank page will open in the Editor. Type in the
following, and save it as squarefun.m to the current directory. Important: The name of
the function (written in bold in the following code) must be the same as the file name,
otherwise the function cannot be called!
function y = squarefun(x)
% Calculate the square of a number
y = x.^2;
end
Some characteristics of the functions are:
plot(x,a,'k',x,b,'b',x,c,'g')
legend('square','x^3','x^4','Location','North')
legend('square','x^3','x^4','Location','Best')
Comments are an important part of multi-line programs. On the one hand, others also
can understand our code, and on the other hand, we will also remember it if we want
to use it again or modify later. It is advisable to write comments not only at the
beginning of the program but also for each new section. In Matlab, you can write
comments after the % sign. For a function, it is useful to specify in the comments what
the purpose of the function is, what input and output values are used. In the case of a
function, the comments written after the first line will be displayed when calling the help
command with this function name.
When writing a script we encounter many error messages, as we have seen some
earlier. It is important that we could interpret these to correct our mistakes!
Let's look a mistyping error in ’clear all’!
cler all
Undefined function or variable 'cler'.
Did you mean:
>> clear all
Matlab is case sensitive:
X = 3/4; x
Undefined function or variable 'x'.
Let's look an example of a syntactically incorrect Matlab statement:
1 X
1 X
↑
Error: Unexpected MATLAB expression.
Wrong number of input parameters:
sin(pi,3)
Error using sin
Too many input arguments.
The number of rows/columns in the matrices does not match:
M = [1 2;3]
Dimensions of matrices being concatenated are not consistent.
[3, 4, 5] * [1; 2; 3; 4]
Error using *
Inner matrix dimensions must agree.
a = 1:5, b = 1:3
[a;b]
Error using vertcat
Dimensions of matrices being concatenated are not consistent.
An easy typing error would be to type 8 or 9 instead of round parentheses:
sin(pi9
sin(pi9
↑
Error: Expression or statement is incorrect--possibly unbalanced (, {, or [.
Missing parenthesis:
abs(sin(rand(2))
abs(sin(rand(2))
↑
Error: Expression or statement is incorrect--possibly unbalanced (, {, or [.
We want to perform element-by-element operation on a vector, but the point is missed:
v =1:4;
1/v
Error using /
Matrix dimensions must agree.
Worst of all, when there is no error message, but the result is still incorrect. Example:
1
Calculate 2𝜋 with the following statement. Why is the result wrong?
1/2*pi % 1.5708
If you decide to use Octave to practice at home, Octave can be downloaded from
https://www.gnu.org/software/octave/, the current version is 5.1.0, which came out on
Mar 1, 2019. The advantage of Octave over education licensed Matlab is that it is an
open source program that can be used not only for educational purposes but also for
work. There are many add-on packages available, see https://octave.sourceforge.io/
and https://octave.sourceforge.io/packages.php, many of them are installed, just need
to be loaded when you want to use them. You can query what is installed with the pkg
list command).
During the numerical methods practices we will perform many symbolic computations
too, which requires installing an extra symbolic package for Octave (this is a separate
toolbox in matlab). This package is based on python-sympy and must be installed
separately. Installation under Windows (link:
https://github.com/cbm755/octsympy/wiki/Notes-on-Windows-installation)
diff (f)
Result ⇒ -sin(x)⋅cos(cos(x))