Вы находитесь на странице: 1из 4

# MATLAB basics

Workspace
On opening MATLAB the Command Window is created . The Command Window is the mechanism through which one can
communicate with the Matlab interpreter. The interpreter displays its prompt ">>" on the right hand side of the screen,
indicating that it is ready to accept instruction. If after entering instructions Matlab Command Window display no ">>"
then is means that Matlab is still executing the commands. Once finished the symbol ">>" will be displayed.
Type 1 at the command line and press return. The program immediately replies with
ans = 1
What has happened is that a variable has been created called ans and the value 1 placed in it.
Repeat the procedure with the number 2.
Many functions are built into MATLAB from the basic package through to the use of numerous toolboxes specific to a
particular application.
Matlab as a Calculator
All the basic arithmetic operators +. -. *, / and ^ are used together with ( ). ^ is used to show the power: 2^3 = 8.
Type in the followings:
>> 3 + 4/6*9
ans = 9
Note: Matlab works according to the priorities as:
1- Quantities in brackets
2- Powers
3- * and / , working left to right
4- + and -, working left to right.
Variables
Scalars: A scalar is a simple variable with one column and one row.
Creating scalars: To create a scalar assign a value to a name. Try the following and verify z. Press return to execute eac line.
>> x = 1;
>> y = 2;
>> z = x + y;
>>z
Scalar operations: MATLAB supports the standard scalar operations using an obvious notation. The following
statements demonstrate scalar addition, subtraction, multiplication and division.
>> u = 5;
>> v = 3;
>> w = u + v
>> x = u - v
>> y = u * v
>> z = u/v
Built-In Functions
There are many functions built into MATLAB e.g. the Trigonometric functions: sin, cos, tan
Try the following.
>> x = 7* cos (pi/4), y = 7 * sin (pi/4) - note the , allows the two commands to be executed with one return press and pi is a contant
provided by MATLAB.
x = 4.9497
y = 4.9497
There are many functions that you can find and try via the help browser.
Vectors and matrices
Most calculations in MATLAB are vector or matrix manipulations by default. Vectors (and matrices) are often built using the
colon separator, which generates a count of values from a start value to a finish value with a particular increment.
Try
>>0:0.1:10
The elements of the vector (matrix) can be typed in individually inside square brackets with rows separated by the semicolon.
Try
>>m = [ 1 2 3;4 5 6]
The elements can be accessed with the row and column number .
Try
>>m(1,1) and note which value it refers to
Try
>>m(3,1) = 10
And then
>>m

Some functions automatically generate vectors with specific features e.g. the linspace and logspace functions create vectors
(row and/or columns) with linearly spaced or logarithmically spaced elements, respectively.
Examples:
>> x = linspace(1,5,5)
x = 1 2 3 4 5
>> y = logspace(1,4,4)
y = 10 100 1000 10000
Having created a vector, it can be assigned to another vector, the ones function creates a 1 by 5 matrix containing all ones. It is then
assigned y.
>> x = zeros(1,5);
>> y = x;
Functions can also be placed inside vectors/matices e.g.
>> b = [1 2, 5 sqrt(6)]
b = 1.0000 2.0000 5.0000 2.4495
>>
Try out the following and notice the difference that spaces can make:
(i) b2 = [2+ 5 4 6] (ii) >> b3 = [2 +5 4 6]
Arithmetic operations as opposed to matrix operations can be done provided the vectors/matrices are the same size, see below:
>> b + b3
ans = 3.0000 7.0000 9.0000 8.4495
Note: b is a vector of 4 elements (one row plus 4 columns).
>> b4=4*b
b4 = 4.0000 8.0000 20.0000 9.7980
>> b5 =2*b -4*b3
b5 = -6.0000 -16.0000 -6.0000 -19.1010
>>
How about b6 = b + b2?
>> b6=b + b2
Vectors can be multiplied by a number (a scalar),
Try
>> w = [ 2 4 7], z = [9 10 11]
>> 5*w
To multiply element by element the dot notation is used
Try
>>w*z
>>w.*z
Transposing Vectors: A row vector can be converted into a column vector (and vice versa) by transposing
the vectors, as shown:
>> w, w'
Complex Numbers
In Matlab complex number is indicated by the special function "i" and "j". For example
Try
>>z = 3 + 4i
>>z = 3 + 4j
>> x = [4+5i 2 4; 1 3+i 7]
Supressing output.
This can make the code execute quicker as it does not have to process the display output;
Example:
>>0:0.0001:1
>>0:0.0001:1;
Editor and M-Files
These are the program files in MATLAB used to develop meaningful programs which encompasses all the necessary
code for a particular application.
Up to now you were using the Matlab in its real time operation mode. That is as you entered the commands, they were
executed immediately and you could observe the results. In this mode if you leave the Matlab you will lose all your
instructions.
If the process requires many different operations, they are typed in a file using an Editor, which is include with MATLAB and works
directly with the MATLAB interpreter.
The matlab files all have the extension .m. For example: miniproject.m.
To use it, from Matlab screen, Click on File, then NEW, and then select script (there are other ways to start the editor and you can
investigate these.

A blank file will appear in front of you. Type the following into the editor and verify z by running from the green arrow button in the
editor.
x=5;
y=2;
z=x*y
Save the file as temp.m to an appropriate directory
This will execute the instruction in the file temp.m. Note you may have to change to the correct path, if the operation is successful you
should see the value of z=10, printed on the screen.
You can save your file and when you exit MATLAB it will be available for a later MATLAB session
Plotting
Plotting is a simple task using the plot function plot() and will automatically plot the elements of a vector e.g. try
>>y = 0:0.1:1;
>>figure(1);plot(y) ;
By default the independent axis uses the vector index number. You can have your own axis numbers
>>x = 10*y;
>>figure(1);plot(x,y) ;
Note so far the variables have always been available in the workspace once created the clear command on its own clears the
workspace of all variable or it can refer to a specific one e.g. clear y
The whos command shows variable currently in the workspace.
Control Structures (Loop and Conditional Statements)
The "For" commands: This allows a command or series of commands to be executed several times. Similar
to the for function in C. Caution: Do not to use the variable i for an index; else, you may inadvertently redefine
sqrt(-1). For example, typing
for x = 1:5
x
end
The Matlab would return:
x=1
x=2
x=3
x=4
x=5
Nested for loops: Every for command must have a matching end statement.
Example:
for m = 1:3
for n = 1:3
x (m,n) = m + n*i;
end
end
Matlab defines x to be the matrix:
x=
1.0000 + 1.0000i 1.0000 + 2.0000i 1.0000 + 3.0000i
2.0000 + 1.0000i 2.0000 + 2.0000i 2.0000 + 3.0000i
3.0000 + 1.0000i 3.0000 + 2.0000i 3.0000 + 3.0000i
The "If" command
Allows you to have programs that make decisions about what commands to execute.
Example:
if a > 0
x = a^2;
end
This command assigns x to be the value of "a" squared, if a is positive.
Note: It must end with end to indicate which commands are actually part of the if.
In addition, one can define an else clause, which is executed if the condition given for the if is not true.
Example:
if a > 0
x = a^2;
else
x = - a^2;
end
For this version, if you had already set a to be 2, then x would get the value 4, but if a was -3, x would be -9.
Note: only one end (after all the clauses of the if) is required.
The if can be expanded to include several possible conditions. If the first condition isn't satisfied, it looks for the next,

## and so on, until it either finds an else, or finds the end.

Example:
if a > 0
x = a^2;
elseif a == 0,
x = i;
else
x = - a^2;
end
Here a is checked to see if it is positive: if not, it is then checks to see whether it is zero; if a is not zero, it does the else
clause. Thus, if a is positive, x well be a squared, if a is 0, x will be i, and if a is negative, then x will be the negative of
a squared.
The "while" command
It allows execution of a group of commands until some condition is no longer true. These commands appear between
the while and its matching end statement.
Example: We want to start x at 2 and keep squaring it until it is greater than one million.
x = 2
while x < 1000000
x = x^2;
end
It runs until x is 4.2950e+09. Everything between the while line and the end is executed until the boolean condition on
the while line is no longer true. One needs to ensure that this condition will eventually stop being true, or the command
will never finish. If it is not initially true, no commands will be executed.
Logical Functions
True or false in Matlab are presented as:
True = 1, false = 0.
The following logical tests may be taken on a particular variable, function etc. Note the use of % for adding comments.
x == 2 %is x equal to 2?
x ~= 2 %is x not equal to 2?
x > 2 %is x greater than 2?
x < 2 %is x less than 2?
x >= %2 is x greater than or equal to 2?
x <= %2 is x less than or equal to 2?
>> x=pi
x = 3.1416
>> x~=3, x~=pi
These can be used for testing purposes in if statements and loops.
Tutorials
For the following tutorial you may use the NOTEPAD Editor. You need to save the file in Matlab directory.
Example 1 Plot two cycles of a sin wave at a frequency of 1 kHz, for the following resolutions
(a) 100 points / cycle, (b) 50 points/ cycle, and (c) 10 points / cycle
Example 2 Add further codes to the example 1 and save the file as example2.m. Plot sine wave against time,
radian and degree. The subplot is used to draw multiple plots on the same figure.
Example 3 Add further codes to the end of example2.m file and save it as example3.m. Plot sine wave from 90 degree to 450 degree,
here you can use the find function in conjunction with logical == to locate values in a vector.