












Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
This matlab tutorial covers the basics of using the matlab desktop, including the command window and help browser. It also introduces simple mathematics, such as variables, mathematical expressions, and build-in functions. Additionally, it explains how to create and use script m-files.
Typology: Study notes
1 / 20
This page cannot be seen from the preview
Don't miss anything!
This is the primary place where you interact with MATLAB. The prompt >> is displayed in this window, and when this window is active, a blinking cursor appears to right of the prompt. This cursor and prompt signify that MATLAB is waiting to perform a mathematical operation. In this window, you can enter variables and mathematical expressions, and run commands and MATLAB codes called M-files.
Practice: Enter
1+ and hit the enter key: ans = 2
x = 1 x = 1
y = 1 y = 1
z = x+y z = 2
The expression x = 1 means that the value 1 is assigned to the variable x. Multiple commands are separated by commas or semicolons, they can be placed on one line:
x = 1, y = 1; x = 1
Commas tell MATLAB to display results; semicolons suppress printing.
Use the Help browser to search and view documentation and demos for all your Math- Works products. The Help browser is a Web browser integrated into the MATLAB desktop that displays HTML documents. To open the Help browser, click the help button in the toolbar, or type helpbrowser in the Command Window. The Help browser consists of two panes, the Help Navigator, which you use to find information, and the display pane, where you view the information. The following are useful commands for online help:
Use the Editor/Debugger to create and debug M-files, which are programs you write to run MATLAB functions. The Editor/Debugger provides a graphical user interface for basic text editing, as well as for M-file debugging. You can use any text editor to create M-files, such as Emacs, and can use prefer- ences (accessible from the desktop File menu) to specify that editor as the default. If you use another editor, you can still use the MATLAB Editor/Debugger for debug- ging, or you can use debugging functions, such as dbstop, which sets a breakpoint. If you just need to view the contents of an M-file, you can display it in the Command Window by using the type function.
For a list of more advanced mathematical and matrix functions, type
help specfun
help elmat
Some of the functions, like sqrt and sin, are built in. They are part of the MATLAB core so they are very efficient, but the computational details are not readily accessible. Other functions, like gamma and sinh, are implemented in M-files. You can see the code and even modify it if you want. Several special functions provide values of useful constants.
pi 3.14159265... i Imaginary unit,
j Same as i eps Floating-point relative precision, 2−^52 realmin Smallest floating-point number, 2−^1022 realmax Largest floating-point number, 2^1023 Inf Infinity NaN Not-a-number
Infinity is generated by dividing a nonzero value by zero, or by evaluating well defined mathematical expressions that overflow, i.e., exceed realmax. Not-a-number is generated by trying to evaluate expressions like 0/0 or Inf-Inf that do not have well defined mathematical values. The function names are not reserved. It is possible to overwrite any of them with a new variable, such as
eps = 1.e-
and then use that value in subsequent calculations. The original function can be restored with
clear eps
Like most other programming languages, MATLAB provides mathematical expres- sions, but unlike most programming languages, these expressions involve entire ma- trices. Here are a few examples, and the resulting values.
rho = (1+sqrt(5))/
rho =
a = abs(3+4i) a = 5
Sometimes expressions or commands are so long that it is convenient to continue them onto additional lines. In MATLAB, statement continuation is denoted by three periods in succession, as shown in the following code:
b = 10/ ... 2 b = 5
Use MATLAB to evaluate the following expressions.
A Matrix can be generated by entering an explicit list of elements
A = [16 3 2 1; 3 5 8 9]
A =
16 3 2 1 3 5 8 9
MATLAB provides four functions that generate basic matrices.
zeros All zeros ones All ones rand Uniformly distributed random elements randn Normally distributed random elements Here are some examples.
B = zeros(2,4)
B =
0 0 0 0 0 0 0 0
F = 5*ones(3,3)
F =
5 5 5 5 5 5 5 5 5
The element in row i and column j of A is accessed by A(i,j).
A(1,3)
ans =
2
The element in row i and column j of B can be changed by
B(1,1) = 1
B =
1 0 0 0 0 0 0 0
C = A’
C =
16 3 3 5 2 8 1 9
B./A+
ans =
1.0625 1.0000 1.0000 1. 1.0000 1.0000 1.0000 1.
B(:,1) = 10
B =
10 0 0 0 10 0 0 0
ans =
16 3 2 1 10 0 0 0 3 5 8 9 10 0 0 0
4 Script M-Files
For script M-files, go to MATLAB Help → Programming and Data Types → M-File Programming. MATLAB is a powerful programming language as well as an interactive compu- tational environment. Files that contain code in the MATLAB language are called M-files. You create M-files using a text editor, then use them as you would any other MATLAB function or command. There are two kinds of M-files:
The first line of a function M-file starts with the keyword function. It gives the function name and order of arguments. In this case, there are one input argument and one output argument. The next several lines, up to the first blank or executable line, are comment lines that provide the help text. These lines are printed when you type help square The first line of the help text is the H1 line, which MATLAB displays when you use the lookfor command or request help on a directory. The rest of the file is the executable MATLAB code defining the function. The function can be used in several different ways.
square(10) y=square(10)
If youre a new MATLAB programmer, just create the M-files that you want to try out in the current directory. As you develop more of your own M-files, you will want to organize them into other directories and personal toolboxes that you can add to your MATLAB search path. If you duplicate function names, MATLAB executes the one that occurs first in the search path. To view the contents of an M-file, for example, square.m, use type square.m
type square.m
function y = square(x) % Compute the square of x % Comments from this line are not displayed when you use the lookfor % command or request help
y = x^2;
5 Basic Plotting
To learn basic plotting, go to MATLAB Help → Getting Started → Graphics. The following example demonstrates how to use the plot function.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Matlab code basic_plotting.m % Plot the graph of a fuction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
x = 0:pi/100:2*pi; y = sin(x); figure(1) plot(x,y) % produce a graph of y versus x
xlabel(’x = 0:2\pi’) %label the axes ylabel(’Sine of x’) title(’Plot of the Sine Function’,’FontSize’,12) %add a title
y2 = sin(x-.25); y3 = sin(x-.5); figure(2) plot(x,y,x,y2,x,y3) %create multiple graphs with a single call to plot legend(’sin(x)’,’sin(x-.25)’,’sin(x-.5)’) % provide an easy way to % identify the individual plots.
x1 = 0:pi/100:2pi; x2 = 0:pi/10:2pi; figure(3) % specify color, line styles, markers, and line width plot(x1,sin(x1),’r:’,x2,sin(x2),’r+’, ’linewidth’, 2)
6 Relational Operators
For the relational operators, go to MATLAB Help → Programming and Data Types → M-File Programming → Operators → Relational Operators. The MATLAB relational operators compare corresponding elements of arrays with equal dimensions. Relational operators always operate element-by-element. When an array is compared with a scalar, the scalar is compared with every element of the array.
7 Logical Operators
For the logical operators, go to MATLAB Help → Programming and Data Types → M-File Programming → Operators → logical Operators.
A = [1 2 0]
A =
1 2 0
B = [0 3 4]
B =
0 3 4
C = A&B
C =
0 1 0
D = A | B
D =
1 1 1
8 Flow Control
For flow control constructs, go to MATLAB Help → Getting Started → Programming with MATLAB → Flow Control.
The if statement evaluates a logical expression and executes a group of statements when the expression is true. The optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, which matches the if, terminates the last group of statements. The groups of statements are delineated by the four keywords–no braces or brackets are involved.
a = 1
a =
1
if a == A = zeros(3,3) else B = ones(4,4) end
A =
0 0 0 0 0 0 0 0 0
a = 0
a =
0
if a == A = zeros(3,3) else
t = 0:0.01:4*pi; y = sin(t); fc = 0; t_length = length(t); for n = 1:10:t_length plot(t(1:n),y(1:n), ’b -’, t(n),y(n), ’r >’, ’linewidth’, 2) xlabel(’t’,’fontsize’, 18); ylabel(’y’,’fontsize’, 18); grid on axis([0 max(t)+0.1 -1.1 1.1]), pause(0.1); str = [’Sine Wave: t = ’ num2str(t(n))]; title(str,’fontsize’, 16); fc = fc+1; F(fc)=getframe(gcf); end
moviename= [’sine_wave.avi’]; movie2avi(F, moviename, ’fps’, 6, ’colormap’, jet, ’quality’, 100)
To find functions of Audio and Audio/Video, go to MATLAB Help → MATLAB →endverbatim Functions - By Category → File I/O → Audio and Audio/Video.
The while loop repeats a group of statements an indefinite number of times under control of a logical condition. A matching end delineates the statements. The following program uses the while loop to compute the sum: 1+2+· · ·+9+10.
sum = 0
sum =
0
n = 1
n =
while n<= sum = sum + n; n = n +1; end sum
sum =
55