Sie sind auf Seite 1von 10

INTRODUCTION TO MATLAB SOFTWARE

What is MATLAB?

Matlab is a contraction for “Matrix Laboratory.” Matlab is programming language and


environment for scientific computing that is centered on matrices. MATLAB is an
interactive, matrix-based system for scientific and engi-neering numeric computation and
visualization. Its strength lies in the fact that complex numerical problems can be solved
easily and in a fraction of the time required by a programming language such as Fortran or C.
It is also powerful in the sense that, with its relatively simple programmingcapability,
MATLAB can be easily extended to create new commands and functions.

What is Command Window?

The interaction with MATLAB is through the command window of its graphical user
interface (GUI). In the command window, the user types MATLAB instructions, which are
executed instantaneously, and the re-sults are displayed in the window.
In the MATLAB command window the characters “ >> ” indicate the prompt which is
waiting for the user to type a command to be executed.
The Command Window Often times you will work at the command line in the command
window. The command window allows you to type commands directly and see the results
immediately.
For example at the >>, define a variable "a" by typing
>> a=[1 2]
What is printed out below is the output of the command
a=
12
What is the Editor Window?

Alternatively you can write a program or script called a m-file (has a .m extension) in the
Editor Window. The Editor Window is a word processor specifically designed for Matlab
commands so it automatically formats certain things for you such as the command "for"
below

This program may consist of one or many commands to execute. Once the program is saved
you can just type the name of the file and all of the commands will execute. It is common to
try a series of commands at the command line and once you like them, copy them from the
Command History and then paste them into a m-file. If you want to make comments that
help explain in English what different code does you put a "%" symbol in front of the text.

Getting Help

Matlab has an incredibly good help system. The help is built into Matlab and can be accessed
from the help menu, but the full help is available online at mathworks.com. Because this
help is so good, it is silly to reproduce everything here. We show some brief descriptions on
commands below, but we expect you to READ THE HELP FILES.
To get help on a command, type "doc commandname" in Command Window where
commandname is the command of interest. For example:
>> doc plot =
Symbols :

Sr. Symbols Role Description Examples


no

@ Function handle The @symbol forms a Create a function handle to a


At construction and handle to either the named function:
symbol reference named function that fhandle = @myfun
follows the @sign, or to Create a function handle to an
the anonymous function anonymous function:
that follows the @sign. fhandle = @(x,y) x.^2 + y.^2;
Create Function Handle
 Decimal
Decimal point:
point
The period character
separates the integral and 102.5543
 Element-
fractional parts of a
wise
number, such as 3.1415. Element-wise operations:
operation
MATLAB operators that
s
contain a period always A.*B
. work element-wise. The A.^2
 Structure period character also
Period or
field enables you to access the
dot Structure field access:
access fields in a structure, as
well as the properties and myStruct.f1
 Object methods of an object.
property Object property specifier:
or
method myObj.PropertyName
specifier

Create a vector:

x = 1:10

Create a vector that increments


by 3:

x = 1:3:19

Reshape a matrix into a column


vector:
 Vector Use the colon operator to
creation create regularly spaced A(:)
vectors, index into arrays,
:  Indexing and define the bounds of Assign new elements without
Colon a forloop. changing the shape of an array:
 For-loop
iteration A = rand(3,4);
A(:) = 1:12;

Index a range of elements in a


particular dimension:

A(2:5,3)

Index all elements in a particular


dimension:

A(:,3)
forloop bounds:

x = 1;
for k = 1:25
x = x + x^2;
end

Separate rows to create an array:

A = [12,13; 14,15]

 Signify Use semicolons to Suppress code output:


end of separate rows in an array
row creation command, or to Y = max(A);
;
suppress the output
Semicolo
n  Suppress display of a line of code. Separate multiple commands on
output of a single line (suppressing
code line output):

A = 12.5; B = 42.7, C = 1.25;


B=
42.7000

Basic Plotting Functions:

Basic Linear Algebra

Key point: It is important to understand the difference between an operator that


operates on each element in an array and one that operators on the whole array.

For example :

>> a=[1 2 3]

a =

1 2 3
>> a*a
??? Error using ==> mtimes
Inner matrix dimensions must agree.

>>

This occurs because the '*' operator is trying to do a type of vector multiplication
called the dot product

If you want to multiply each entry in a then you should try:

>> a.*a

ans =

1 4 9

But Matlab is smart enough to multiply a vector by a scalar so you can do:

>> a*3

ans =

3 6 9

Manipulating Matrices

Elements in arrays are addressed by their rows and columns numbers, using a
semicolon to extend a range. For example:

>> a = [ 1 4 7; 2 8 5] %build a matrix

a =

1 4 7
2 8 5

>> a(2,3) %reference the elements in the second row,


third column

ans =

>> a(:,2) %reference all the elements in the second


column
ans =

4
8

>> a(1:2,2:3) %reference the elements in the first and


second rows and second and third columns

ans =

4 7
8 5

Matlab editor
Matlab is not only a powerful language, but also features an excellent Integrated
Development Environment, including a powerful
editor, debugger, profiler, compiler, etc. In this chapter, we discuss the editor,
which is the recommended way to interact with matlab.

Contents

 Editor
 Cells
 Code folding
 Layouts and Other Windows
 Shortcuts
 Web browser
 Workspace
 Current Directory

Editor

As we mentioned, Matlab commands are executed either at the command prompt


or by running scripts or functions, which can be created and edited with the built in
editor. To launch the editor, if it is not already open, type edit or edit filename.
Commands can be entered here and executed as a script. They are saved with a .m
extension. To run your script, type in the name at the command prompt, or
press F5 or the save and run button at the top of the editor. Your own functions
can be written here as well, as discussed here. You can set break points to halt
execution at certain lines for debugging, which we discuss here.
Here is an image of the editor in action. Notice we have the open m-files listed in
the center column; you can move these to the left right or bottom. We have
also docked one of the figures in the top left. By default figures open in their own
windows but it can sometimes be useful to work with a figure on the same screen:
to do this, use the doc window arrow at the the top left of the figure.

There are many other configuration options and editor tools available; experiment
by selecting the many buttons and exploring the drop down menus.

Cells

You can partition your code into editor cells by typing two percent signs, %%, at
the beginning of the line. This can help organize your code into logical sections.
You can also evaluate cells one at a time by selecting the evaluate cell button at the
top of the editor. At any time, you can execute an arbitrary block of code by
highlighting it and pressing F9. Cells are also used when publishing your code.
This tutorial was written in Matlab and published to html by selecting
the publish button at the top of the editor. This can be very useful when you want
to share your code and results with others in a professional looking report.

Code folding

Certain constructs like for loops and functions can be folded, hiding all but the top
line from view. Select the + or - symbols appearing on the left hand side of the
editor, by the line numbers.

Layouts and Other Windows

Matlab gives you a lot of freedom over how you organize the windows in the
environment. For instance, you can have have multiple windows take up the same
screen area and toggle between them at will, or place windows at the sides where
they automatically hide until you select them. Try dragging them around to
different places to see the effect. There are more windows than described here
available under the Desktop drop down menu.

You can save the current layout, select one of the default ones, tile all the
windows, and perform many other related tasks under the Desktop drop down
menu. Its worth taking the time to organize your layout effectively before you
begin working.

Shortcuts
You can add shortcut buttons to the toolbar, which can be a useful alternative to
editing the startup file. right click on Shortcuts then select new shortcut; give it a
label (name) and enter the commands you want to run when you click on it.

Web browser

You can read web pages from inside matlab. Just type something like web
www.cs.ubc.ca/~murphyk/matlabTutorial/html/index.html. This is particularly
useful for matlab-generated web pages, such as this tutorial. You can execute code
by highlighting it on the web page and pressing F9. The statements are processed
as though they were typed one at a time in the command window.

Workspace

All of the current variables, as well as basic information about them, can be viewed
in a convenient graphical window called the workspace (see below). If it is not
already visible, you can bring it up by typing workspace at the command prompt
or by going to the desktop drop down menu. You can then drag and place it
wherever it is convenient. You can set what information you want displayed by
right clicking on the header bar (with "Name Value Class Size Bytes" in the picture
below). If you double click on a variable it will open it in the variable editor where
you can inspect or change its values.

Current Directory

The current directory window, unsurprisingly, displays the files in the current
working directory. You can open it via the drop down menu Desktop->Current
Directory if it is not already open. From here you can navigate the file system and
search for files. Type F5 to force a refresh.

x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);
p = plot(x,y1,x,y2);
x = linspace(0,10,150);
clc;
clear all;
close all;
x = linspace(0,10,150);
y = cos(5*x);
figure
plot(x,y,r,'*')

title('2-D Line Plot')


xlabel('x')
ylabel('cos(5x)')

x1=sawtooth(t);

subplot(2,2,1);

title('Sawtooth Wave');
xlabel('t');
ylabel('Amplitude');

x2=square(t);

subplot(2,2,2);

title('Square Wave');
xlabel('t');
ylabel('Amplitude');

x3=sin(t);

subplot(2,2,3);

title('Sine Wave');
xlabel('t');
ylabel('Amplitude');

x4=cos(t)

subplot(2,2,4);

title('Cosine Wave');
xlabel('t');
ylabel('Amplitude');