You are on page 1of 12

Programming.

Bachelor in Aerospace Engineering

Lab sessions
Work in pairs, not to both of it just half of the work, but to work together as a team
helping each other. Nevertheless, do not hesitate to ask to your mate if you has a
question, as trying to explain something is the best way to learn it. And of course can
always ask to your teacher.
The steps for this very first session are the following:
1.
2.
3.
4.

Switch on both the screen and the computer


Login into the system: Type your NIU and your password
Follow the guide notes (see pdf file). Read it carefully
Do the exercises at the end of the guide notes
a. If you cannot do all of them in this session, do them in individual
sessions before next lab sessions
b. You can ask your questions in course forum
5. Write down a small exercise at the end of the session.
6. Finally, before leaving the lab session: 1) log off and 2) switch off only the
monitor (not PC)

Programming.
Bachelor in Aerospace Engineering

Introduction to the Matlab Environment


MATLAB is a mathematical and graphical software package with numerical, graphical,
and programming capabilities.

Starting...
Open up MATLAB for Windows
Through the START Menu
When the MATLAB software is started, a window opens in which the main part is the
Command Window (see Figure 1). In the Command Window, you should see the
symbol >>.

Figure 1. MATLAB environment (R2011a)


The >> is called the prompt. In the Command Window, MATLAB can be used
interactively. At the prompt, any MATLAB command or expression can be entered, and
MATLAB will respond immediately with the result.
In addition to the Command Window, there are several other windows that can be
opened and may be opened by default. To the left of the Command Window is the

Programming.
Bachelor in Aerospace Engineering

Current Folder Window. The folder that is set as the Current Folder is where files will
be saved. This window shows the files that are stored in the Current Folder. To the
right of the Command Window are the Workspace Window on top and the Command
History Window on the bottom. The Command History Window shows commands that
have been entered, not just in the current session (in the current Command Window),
but previously as well.
The following commands can serve as an introduction to MATLAB and allow you to get
help:
demo will bring up MATLAB examples in the Help Browser, which has examples
of some of the features of MATLAB.
help will explain any function; help help will explain how help works. Probably
the most useful command.
lookfor searches through the help for a specific word or phrase.
doc will bring up a documentation page in the Help Browser.
clc clears all input and output from the Command Window display, giving you
a "clean screen."
matlabroot returns the name of the folder where the MATLAB software is
installed.
pwd displays the MATLAB current folder.

TIP:
A very useful hotkey is Tab, as it will complete your current command. Tab
Completion is a popup that can be found in both the Command Window and
the Editor. After you type a key (or a few) you can hit the tab key and a popup
will appear and show you all of the possible completions, including variable
names and figure properties.

First steps
A good programming practice is to use folders to keep your programs organized. To
make a new folder, click the Browse button next to Current Folder. Click the Make
New Folder button, and change the name of the folder. Do NOT use spaces in folder
names. The current directory is now the folder you just created

Programming.
Bachelor in Aerospace Engineering

MATLAB can be thought of as a super-powerful graphing calculator. When you


introduce an operation or expression at the prompt, you will obtain the result:
>> 10 / 3
ans =
3.3333
>>
To store a value in a MATLAB session, or in a program, a variable is used. Variables can be seen
as a piece of the memory to store a piece of data. One easy way to create a variable is to
simply assign a value to a name. The format of an assignment statement is:

variableName = expression
The variable is always on the left, followed by the = symbol, which is the assignment
operator, followed by an expression. Assigning a value to a variable means that the value on
the right is stored on the variable on the left. A single value or the result of an expression can
be assigned: variable value or expression.

For example:
>> num = 5
num =
5
>>
A variable can be assigned several times, being the previous value overwritten.
Putting a semicolon at the end of a statement suppresses the output after each
command:
>> num = 5;
>>
The Workspace Window shows the variables that have been created and their values.
MATLAB uses a default variable named ans if an expression is typed at the prompt and
it is not assigned to a variable:
>> 2 + 2
ans =
4
>>

Programming.
Bachelor in Aerospace Engineering

This default variable is reused any time only an expression is typed at the prompt.
TIP:
A shortcut for retyping commands is to hit the up arrow , which will go back
to the previously typed command(s).
Every variable has:

Name, i.e. a label or identifier of the symbol

radius, area, PI

Type, determines which values that can be assigned to the symbol


integer number, real number, single letter,

Value, value of the symbol at a given moment


2, 12.566360

Note:
pi (lowercase) is a reserved word just for the value 3.1415 . Try to type
within command window each of the following and then press Intro (but only
one at a time):
pi, PI, Pi, pI

Using, naming and initializing variables


Variable names are examples of identifier names. There are several rules for identifier
names:
1. the first character must be a letter of the alphabet.
2. after that, any combination of letters, numbers and the symbol _ , but it
cannot have a space.
3. MATLAB is case-sensitive, which means that there is a difference between
upper- and lowercase letters (var2 is different from Var2; pi and PI are also
different).
4. there are certain words called reserved words, or keywords, that cannot be
used as variable names.

Programming.
Bachelor in Aerospace Engineering

The following commands relate to variables:


clear, clears out all variables so they no longer exist.
clear VarName, clears out a particular variable.
clear VarName1 VarName2 , clears out several at the same time. All the
variables names must be separated with spaces.
who, shows the names of the variables defined in this Command Window.
whos, is similar to who, but shows more information on the variables.
A variable can be given a value explicitly when it is created, it is called initialization.
TIP:
It's possible to create and initialize several variables in single line. For
example:
>> x = 1; y = 2; z = 3;

Numerical expressions
Expressions can be created using values, variables that you have already created,
operators and parentheses. For numbers, these can include operators, such as
multiplication, and functions, such as trigonometric functions (for instance sin() and
cos() functions) . An example of such an expression is:
>> 2 * sin(1.4)
ans =
1.9709
>>

Exercise
Create and initialize a variable called myNum. How would you increment the variable
myNum by 1?

Operators and precedence rules


There are, in general, two kinds of operators: unary operators, which operate on a
single value, or operand, and binary operators, which operate on two values or
operands. Here are some of the common operators that can be used with numerical
expressions:
+

addition

Programming.
Bachelor in Aerospace Engineering

negation, subtraction

multiplication

division (divided by e.g. 10/5 is 2)

division (divided into e.g. 5\10 is 2)

exponentiation (e.g. 5^2 is 25)

Some operators have precedence over others. For example, in the expression 4 + 5 * 3,
the multiplication takes precedence over the addition, so, first 5 is multiplied by 3,
then 4 is added to the result. Using parentheses can change the precedence in an
expression:
>> 4 + 5 * 3
ans =
19
>> (4 + 5) * 3
ans =
27
>>
Within a given precedence level, the expressions are evaluated from left to right.
Nested parentheses are parentheses inside of others; the expression in the inner
parentheses is evaluated first. For example, in the expression:
5-(6*(4+2))
First the addition is performed, then the multiplication, and, finally, the subtraction, to
result in -31. Parentheses can also be used simply to make an expression clearer. For
example, in the expression:
((4+(3*5))-1)
The parentheses are not strictly necessary, but are used to show the order in which
the parts of the expression will be evaluated and for readability purposes. For the
operators that have been covered thus far, the following is the precedence (from the
highest to the lowest):
()

parentheses

exponentiation

negation

*, /, \ all multiplication and division


+, -

addition and subtraction

Programming.
Bachelor in Aerospace Engineering

Example
a = 19; b = 23;
x=1; y = 13,45;
z = a*x + b*y; % This is NOT an equation,
% but an

assignment instruction.

% First of all the expression (a*x + b*y) is computed,


% and only then, this value is assigned

% (with assign operator =


% to variable z

Exercise
Think about what the results would be for the following expressions, and then type
them in to verify your answers:
10-6/2

1\2

5*4/2*3

- 5 ^ 2

5-2^2

(-5) ^ 2

5*-2^2

- 5 ^ - 210-6/2

5*4/2*3

1\2

5-2^2

- 5 ^ 2

5*-2^2

(-5) ^ 2
- 5 ^ - 2

Programming.
Bachelor in Aerospace Engineering

Exercise
Check the results for the following numerical expressions:
x = 1;
y = 2;
z = 3;
result_1 = x/y^3-1+2*z;
result_2 = x/y^(3-1)+2*z;
result_3 = (x/y)^(3-1+2)*z;
result_4 = x-1^3+2*z;
What is the explanation for those results? What is the operator with the highest
precedence level in each case?

Basic Input/Output
Programs receive input data (e.g., keyboard) and provide output data (e.g., screen).
Input and output (I/O) functions allow reading and printing data. Input statements
read in values from the default or standard input device, which in our case is the
keyboard, so the input statement reads in values that have been entered by the user.
The simplest input function in MATLAB is called input. When you use it, you have to
include a string in the call. This string is the prompt and will appear on the screen.
Whatever the user types will be stored in the variable named on the left of the
assignment statement.
For example:
>> myVar = input('Give me a value:')
Give me a value:13
myVar =
13
>> myVar2 = input('Give me a value:');
Give me a value:13
note: see the value of myVar2 in Workspace window
Output statements display text, values and the results of expressions. The simplest
output function in MATLAB is disp, which is used to display strings and single variables
to the screen, without a format. The general form of the function is: disp (string or
variable_name). For example:
>> disp('Hello world!')

Programming.
Bachelor in Aerospace Engineering

Hello world!
>> disp(4^3)
64
>> a = 15;
>> disp(a);
15

Exercises
1. As a summary write down a diagram/scheme with the more relevant things
that you have learned this session
2. Write some code to declare three variables (a, b, c), assign the values 5, 7, 9
(respectively), and calculates the sum of them. Modify the code to read the
values from the keyboard.
3.

What is the difference between the commands clc and clear?

4. Write a code snippet to calculate the interest gained after a bank deposit. The
program must ask the initial amount and the interest rate.
5. Write a code snippet that declares two variables (a, b), assigns them two values
read from the keyboard, and swap their values. Print their values before and
after the exchange.
6. Write a code snippet to guess both of you (your classmate and yourself) the
height (in meters) and the weight of your teacher; then compute and show the
value of his/her body mass index.
7. Use the command help to learn about the command mod. Then, write the
commands and expression required to ask for a time value (in seconds) and
transforms it into hours, minutes and seconds.
8. What happens if you use the name of a function, for example, cos, as a variable
name? What happens if you use again the function to get the cosine of Pi?
9. Use the help function to find out what the rounding functions fix, floor, ceil, and
round do. Then ask the user for a number n.

Round up n and store it in u.


Round down n and store it in d.
Round n to the closest integer and store it in r.

Programming.
Bachelor in Aerospace Engineering

References
Attaway, S. (2012). MATLAB: a practical introduction to programming and problem
solving. Elsevier.
Pratap, R. (2009). Getting started with MATLAB: a quick introduction for scientists and
engineers. Oxford University Press, Inc.
The Mathworks Inc. MATLAB Programming Fundamental R2014a [link]
Proquest Safari Books Online http://proquest.safaribooksonline.com/search?q=Matlab

Programming.
Bachelor in Aerospace Engineering

Intro to Matlab Main (some notes from students questions)

Question why is necessary (or what are the difference) a = input ()


and x = 1?

Write snippet source code means type a sequence of commands. If you want
you can type it previously in notepad ++.

For each exercise type (write down) the sequence of commands/instructions


into any text or word file (notebook).

Additional homework
Before type following instructions/commands, what do you think will be the output
shown in command window?
x = 2; y = 3.2;
z = 12*x +2.4 * y;
disp(x= ); disp(x);
disp(y= ); disp(y);
disp(z= ); disp(z);
x = 3; y = 4;
disp(x= ); disp(x);
disp(y= ); disp(y);
disp(z= ); disp(z);

Intro to Matlab Main Issues to learn from this session

Concept of variable

Assignment Instruction
(different than the idea of equation)

Operator Precedence (the same than in math)

Swap the value of variables

Basic Input/Output

Small Programs as a sequence of instructions/commands in Command


Window

Write source code for a program without any (initial) help, only the statement
of the problem

You might also like