Professional Documents
Culture Documents
ماتلاب
ماتلاب
Introduction
What Is MATLAB? (p. 1-2) See how MATLAB® can provide solutions for you in technical
computing, what are some of the common applications of
MATLAB, and what types of add-on application-specific
solutions are available in MATLAB toolboxes.
MATLAB Documentation (p. 1-4) Find out where to look for instruction on how to use each
component of MATLAB, and where to find help when you need
it.
Starting and Quitting MATLAB Start a new MATLAB session, use the desktop environment,
(p. 1-6) and terminate the session.
1 Introduction
What Is MATLAB?
MATLAB® is a high-performance language for technical computing. It
integrates computation, visualization, and programming in an easy-to-use
environment where problems and solutions are expressed in familiar
mathematical notation. Typical uses include
1-2
What Is MATLAB?
Development Environment. This is the set of tools and facilities that help you use
MATLAB functions and files. Many of these tools are graphical user interfaces.
It includes the MATLAB desktop and Command Window, a command history,
an editor and debugger, and browsers for viewing help, the workspace, files,
and the search path.
Graphics. MATLAB has extensive facilities for displaying vectors and matrices
as graphs, as well as annotating and printing these graphs. It includes
high-level functions for two-dimensional and three-dimensional data
visualization, image processing, animation, and presentation graphics. It also
includes low-level functions that allow you to fully customize the appearance of
graphics as well as to build complete graphical user interfaces on your
MATLAB applications.
The MATLAB External Interfaces/API. This is a library that allows you to write C and
Fortran programs that interact with MATLAB. It includes facilities for calling
routines from MATLAB (dynamic linking), calling MATLAB as a
computational engine, and for reading and writing MAT-files.
1-3
1 Introduction
MATLAB Documentation
MATLAB provides extensive documentation, in both printed and online
format, to help you learn about and use all of its features. If you are a new user,
start with this Getting Started book. It covers all the primary MATLAB
features at a high level, including many examples.
The MATLAB online help provides task-oriented and reference information
about MATLAB features. MATLAB documentation is also available in printed
form and in PDF format.
1-4
MATLAB Documentation
For more information about using the Help browser, see Chapter 6, “Desktop
Tools and Development Environment.”
1-5
1 Introduction
For More Information See “Starting MATLAB” in the Desktop Tools and
Development Environment documentation.
Quitting MATLAB
To end your MATLAB session, select File -> Exit MATLAB in the desktop, or
type quit in the Command Window. You can run a script file named finish.m
each time MATLAB quits that, for example, executes functions to save the
workspace, or displays a quit confirmation dialog box.
For More Information See “Quitting MATLAB” in the Desktop Tools and
Development Environment documentation.
1-6
Starting and Quitting MATLAB
MATLAB Desktop
When you start MATLAB, the MATLAB desktop appears, containing tools
(graphical user interfaces) for managing files, variables, and applications
associated with MATLAB.
The following illustration shows the default desktop. You can customize the
arrangement of tools and documents to suit your needs. For more information
about the desktop tools, see Chapter 6, “Desktop Tools and Development
Environment.”
1-7
MATLAB Tutorial
First, let's talk about how we add comments (such as this line) to a program. Comments are
lines of text that we want to add to explain what we are doing, so that if we or others read
this code later, it will be easier to figure out what the code is doing. In a MATLAB file, if a
percentage sign, , appears in a row of text, all of the text following the sign is a comment that
MATLAB does not try to interpret as a command. First, let us write a message to the screen to
say that we are beginning to run section 1.1.
This command both allocates a space in memory for the variable x, if x has not already been
declared, and then stores the value of 1 in the memory location associated with this variable.
It also writes to the screen "x = 1". Usually, we do not want to clutter the screen with output
such as this, so we can make the command "invisible" by ending it with a semi-colon. As an
example, let us use the following commands to "invisibly" change the value of x to 2 and then
to write out the results to the screen. x=2; this changes the value of x but does not write to
difference = z - y
Next, we want to see the list of variables that are stored in memory. To do this, we use the
command "who".
who;
These commands can be used also to get information about only certain variables.
whos z difference;
It is generally good programming style to write only one command per line; however, MATLAB
does let you put multiple commands on a line.
x = 5; y = 13; w = 2*x + y; who;
More commonly one wishes to continue a single command across multiple lines due to the
length of the syntax. This can be accomplished by using three dots.
z = 2*x + ...
y
Finally, when using clear we can get rid of all of the variables at once with the command "clear
all".
clear all;
who; It does not print out anything because there are no variables.
The simplest, but NOT RECOMMENDED, way to declare a variable is by entering the
components one-by-one.
x(1) = 1;
x(2) = 4;
x(3) = 6;
x display contents of x
It is generally better to declare a vector all at once, because then MATLAB knows how much
memory it needs to allocate from the start. For large vectors, this is much more efficient.
y = [1 4 6] does same job as code above
Note that this declares a row vector. To get a column vector, we can either use the transpose
(adjoint for complex x) operator xT = x'; takes the transpose of the real row vector x or, we
can make it a column vector right from the beginning
yT = [1; 4; 6];
To see the difference in the dimensions of a row vs. a column vector, use the command "size"
that returns the dimensions of a vector or matrix.
size(xT)
size(y)
size(yT)
The command length works on both row and column vectors.
length(x), length(xT)
We can also use the . operator to tell MATLAB to perform a given operation on an element-by-
element basis. Let us say we want to set each value of y such that y(i) = 2*x(i) + z(i)^2 + 1.
We can do this using the code
y = 2.*x + z.^2 + 1
clear x y;
who;
It is generally good programming style to write only one command per line; however, MATLAB
does let you put multiple commands on a line.
x = 5; y = 13; w = 2*x + y; who;
More commonly one wishes to continue a single command across multiple lines due to the
length of the syntax. This can be accomplished by using three dots.
z = 2*x + ...
y
Finally, when using clear we can get rid of all of the variables at once with the command "clear
all".
clear all;
who; It does not print out anything because there are no variables.
The simplest, but NOT RECOMMENDED, way to declare a variable is by entering the
components one-by-one.
x(1) = 1;
x(2) = 4;
x(3) = 6;
x display contents of x
It is generally better to declare a vector all at once, because then MATLAB knows how much
memory it needs to allocate from the start. For large vectors, this is much more efficient.
y = [1 4 6] does same job as code above
Note that this declares a row vector. To get a column vector, we can either use the transpose
(adjoint for complex x) operator xT = x'; takes the transpose of the real row vector x or, we
can make it a column vector right from the beginning
yT = [1; 4; 6];
To see the difference in the dimensions of a row vs. a column vector, use the command "size"
that returns the dimensions of a vector or matrix.
size(xT)
size(y)
size(yT)
The command length works on both row and column vectors.
length(x), length(xT)
We can also use the . operator to tell MATLAB to perform a given operation on an element-by-
element basis. Let us say we want to set each value of y such that y(i) = 2*x(i) + z(i)^2 + 1.
We can do this using the code
y = 2.*x + z.^2 + 1
The dot and cross products of two vectors are calculated by
dot(x,y)
z=cross(x,y)
We can define a vector also using the notation [a : d : b]. This produces a vector a, a + d, a +
2*d, a + 3*d, ... until we get to an integer n where a + n*d > b. Look at the two examples.
v = [0 : 0.1: 0.5];
v2 = [0 : 0.1: 0.49];
If we want a vector with N evenly spaced points from a to b, we use the command
"linspace(a,b,N)".
v2 = linspace(0,1,5)
Sometimes, we will use a vector later in the program, but want to initialize it at the beginning
to zero and by so doing allocate a block of memory to store it. This is done by
v = linspace(0,0,100)'; allocate memory for column vectors of zero
Finally, we can use integer counting variables to access one or more elements of a matrix.
v2 = [0 : 0.01 : 100];
c=v2(49)
w = v2(65:70)
clear all
For a complex matrix, ' returns the adjoint (transpose and conjugate. The conjugation
operation is removed by using the "transpose only" command .'
E = D;
E', E.'
The "who" command lists the matrices in addition to scalar and vector variables.
who
If in addition we want to see the dimensions of each variable, we use the "whos" command.
This tells use the size of each variable and the amount of memory storage that each requires.
whos
size(M)
num_rows = size(M,1)
num_columns = size(M,2)
We can create a matrix with m rows and n columns, all containing zeros by
m=3; n=4;
C = zeros(m,n)
We create an Identity matrix, where all elements are zero except for those on the principle
diagonal, which are one.
D = eye(5)
Finally, we can use the . operator to perform element-by-element operations just as we did for
vectors. The following command creates a matrix C, such that C(i,j) = 2*A(i,j) + (B(i,j))^2.
C = 2.*A + B.^2
Matrices are cleared from memory along with all other variables.
clear A B
whos
clear all
who
1
SCIENTIFIC COMPUTING
LECTURE # 2
Matrices
2
Subscripts
Scalar
Vector
Array (Matrix)
Matrix size:
5
The size of A is 1 1
Size of B is 1 2
Size of C is 2 2
Example:
A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
MATLAB displays:
A is a magic square matrix which take the sum along any column or row, or along either of
the two diagonals, you will always get the same number.
Let us verify that using Matlab: sum(A)
Entering Matrices
8
Continuation
Example:
sum(A(:,end))
computes the sum of the elements in the last column of A which is 34
as A is magic matrix.
Test your self
16
Let:
A =
2 9 -3 10
-4 13 1 6
Variable names consist of a letter, followed by any number of letters, digits, or underscores.
MATLAB is case sensitive; it distinguishes between uppercase and lowercase letters. A and a
are not the same variable.
To view the matrix assigned to any variable, simply enter the variable name.
Numbers
20
Some of the functions, like sqrt and sin, are built in.
Built-in functions 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.
There are some differences between built-in functions and other
functions. For example, for built-in functions, you cannot see the code.
For other functions, you can see the code and even modify it if you
want.
Functions
24
Generating Matrices
MATLAB provides four functions that generate basic matrices.
Here are some examples:
26
Concatenation
27
o sum(B) , Its column sums are the correct value for an 8-by-8 magic
square, result in :
Deleting Rows and Columns
29
➢ You can delete rows and columns from a matrix using just a pair of
square brackets.
➢ Start with
➢ Then, to delete the second column of X, use
➢ This changes X to
Deleting Rows and Columns
30
➢ If you delete a single element from a matrix, the result is not a matrix
anymore. So, expressions like
➢ Result in :
31
Any Questions
1
SCIENTIFIC COMPUTING
LECTURE # 3
Summary from Previous Week
2
What Is MATLAB?
◼ MATLAB (MATrix LABoratory)
◼ high-performance language for technical computing
◼ computation, visualization, and programming in an easy-to-use
environment
Summary from Previous Week
3
A = [2 7 4] A = [2 7 4; 3 8 9]
A = [2; 7; 4] B= [ A A]
Matrices
11
A = [2 7 4] A = [2 7 4; 3 8 9]
A = [2; 7; 4] B= [ A A]
Matrices
12
Matrices
13
B = A .* A prints
A matrix can be indexed using another matrix, to produce a subset of its elements:
a = [100 200 300 400 500 600 700] b = [3 5 6]
c = a(b):
300 500 600
To get a subsection of a matrix, we can produce the index matrix with the colon
operator:
a (2 : 5)
Prints: ans= 200 300 400 500
This works in 2-D as well, e.g. c(2:3, 1:2) produces a 2 x 2 submatrix.
The rows and columns of the submatrix are renumbered.
Manipulating Matrices
15
◼ Create matrices A and B and try out the matrix operators in this slide
The colon “:” Operator and the function linspace
16
Elementary math functions
17
Elementary math functions
18
19
Any Questions
1
SCIENTIFIC COMPUTING
LECTURE # 6
MATLAB built-in functions
• Introduction
• Mathematical Functions
• Data Analysis Functions
Introduction
MATLAB has a large number useful of built-in functions
◦ We already saw some examples :
like input, disp, fprintf, zeros, ones
3
Understanding a function call through
an example…..
Computes the
Consider sqrt(100)
square toot of a
number
4
Understanding a function call through
an example…..
Consider sqrt(100)
• The function name is sqrt
5
Understanding a function call through
an example…..
Consider sqrt(100)
• The function name is sqrt
6
Understanding a function call through
an example…..
Consider sqrt(100)
• The function name is sqrt
7
Understanding a function call through
an example…..
• The argument can be a variable
• And the results can be stored in a variable
>> x = 9;
>> sqrt(x)
ans =
3
>> y = sqrt(x)
y=
3
8
Understanding a function call through
an example…..
• The output of a function call can be the argument of
another function call (nested calls)
>> x = 10000;
Inner function
>> sqrt(sqrt(x)) Outer function call
ans = call
10
>> fprintf(‘square root of %d is %d\n’,x,sqrt(x));
square root of 10000 is 100
9
• sqrt also accepts vectors and matrices as input
• Example:
Sqrt([1, 4, 9])
10
Functions that work in a similar manner
• - Use
• >> help functionName
• to get help about a specific function
• Search MATLAB documentation or textbook index to
find the function you need
• Table at the end of Ch3 is a good reference
11
Example of functions with two parameters
- rem
• rem(x,y) : computes the remainder of the
devision x / y
>> x = 10;
>> rem(x,4)
ans =
2
12
Example of functions with two parameters
- rem
• rem(x,y) : if x is a matrix or vector and y is a
scalar works like matrix by scalar operators
0 1 2 3 0
13
Example of functions with two parameters
- rem
• rem(x,y) : if x is a matrix or vector and y is a
matrix works like matrix by element by
element operators (ex: .*, ./)
>> x = [8, 9, 10, 11, 12];
>> y = [3, 4, 3, 4, 3];
>> rem(x,y) rem(10,3)
ans =
rem(12,3)
2 1 1 3 0
rem(8,3) rem(9,4)
14
Functions that work in a similar manner
15
Data Analysis Functions - through an example
• y = sum(x)
• If x is a vector y is the sum of elements in
x
16
Data Analysis Functions - through an example
• y = sum(x)
• If x is a vector y is the sum of elements in x
• If x is a matrix y is the vector of sums of
elements in each column in x
>> x = [8 9 10 ; 20 20 20]; 2 rows
>> y = sum(x)
y = 9+20
28 29 30
10+20
8+20
17
Functions that work in a similar manner
18
More on max and min
• [a,b] = max(x)
• If x is a vector a is the largest elements in x
• b is the location of a in x
• [a,b] = max(x)
• If x is a matrix a is the vector containing largest
of element in each column in x
• b is the location of each element in a
• [a,b] = max(x)
• If x is a matrix a is the vector containing largest
of element in each column in x
• b is the location of each element in a
1 2 1
10 is 2nd number in column 2
21
Any Questions
1
SCIENTIFIC COMPUTING
LECTURE # 7
User-defined functions
• Introduction
• M-Files
• Syntax of user-defined functions
• Calling user-defined functions
Introduction
Functions are M-files that can accept input arguments
and return output arguments.
The names of the M-file and of the function should be
the same.
Functions operate on variables within their own
workspace, separate from the workspace you access at the
MATLAB command prompt.
3
M-Files
M-Files are text files containing MATLAB code.
Use the MATLAB Editor or another text editor to create a
file containing the same statements you would type at
the MATLAB command line.
Save the file under a name that ends in .m.
4
M-Files Cont.
There are two kinds of M-files:
1. Scripts
2. Functions
which can accept input arguments and return output
arguments.
Internal variables are local to the function.
5
M-Files Cont.
6
Script Example
Write the
statements at new
script named
script1.m
7
Script Example Click run to execute
script statements
8
Script Example
if we type the
variable name the
values appear
9
Syntax of user-defined functions
function returnVar = name ( parameters )
body
end
10
User-defined function(Example)
function volume = boxVolume ( paperW , paperL )
height = 2;
length = paperL – 4;
width = paperW – 4;
volume = length * width * height;
end
11
Function in m-file editor
12
Function in m-file editor
13
Function in m-file editor
14
Function in m-file editor
Some functions
do not return
any output
Example : A
modified
version of
boxVolume that
calculates and
prints the
volume
There is no output variable and = sign
before the function name
15
Function in m-file editor
Some functions
return more
than one output
Example : A
function that
returns all
computed
dimensions in
the box volume
problem
16
Calling user-defined functions
Save it in a file with name same as the function name
ends with .m (Ex. boxVolume.m ).
Make sure the file is in the current directory or in a
directory on the path.
Call it from the command line or a script.
17
Calling user-defined functions
18
Any Questions
SCIENTIFIC COMPUTING
LECTURE # 8
RELATIONAL OPERATORS &
LOGICAL OPERATORS
Relational operators
A relational operator performs a comparison and returns true or false
(Boolean values)
Examples
1 > 2 False
(12/4) == 1.5*2 True
In MATLAB
true is represented as 1
false is represented as 0
Relational Operators in MATLAB
>> y = 10;
>> rem(x,5) == 0 & rem(y,5) == 0
ans =
Requires both conditions
to be 1 (true) to give 1
0 (true)
as an answer
and (&) example
>> x = 2;
>> y = 10;
>> rem(x,5) == 0 & rem(y,5) == 0
ans =
0
or (|) example
>> x = 2; 0 1
>> y = 10;
>> rem(x,5) == 0 | rem(y,5) == 0
ans =
Requires at least one
condition to be true to
1 give an true as an
answer
10
Any Questions
SCIENTIFIC COMPUTING
LECTURE # 9
IF STATEMENTS
What’s the use of relational and logical operators?
Examples:
Given a set of genes and their expressions, get all
genes with expression higher than a specific level.
In a pass fail course, give all students with total grade
>= 60 a letter grade P and students with total grade
< 60 a letter grade of F.
Schedule payday for employees based on the first
letter of their last names.
Set the room A/C temperature based on the time of the
day.
How to make use of relational and logical
operators?
Programming constructs /functions that makes use of
relational and logical operators
if statements
find function
loops
Today we will look at selections through
if statements
Input 1 Input 2
______ ______
______ ______
______ ______
______ ______
______ ______
______ ______
______ ______
______ ______
______ ______
The if statement syntax
if condition
commands
end
if statement example
Program LetterGrade
condition
command(s)
>> LetterGrade
Worksapce
if statement example
Program LetterGrade
>> LetterGrade
Worksapce
Input your total grade Grade = 85
if statement example
Program LetterGrade
true
>> LetterGrade
Worksapce
Input your total grade 85 Grade =85
grade 85
if statement example
Program LetterGrade
>> LetterGrade
Worksapce
Input your total grade 85 Grade =85
grade 85
Your letter grade is P
if statement example
Program LetterGrade
false
>> LetterGrade
Worksapce
Input your total grade 85 Grade =85
grade 85
Your letter grade is P
if statement example
Program LetterGrade
skip
>> LetterGrade
Worksapce
Input your total grade 85 Grade =85
grade 85
Your letter grade is P
if-else statement example
Program LetterGrade2 : a better version of LetterGrade
>> LetterGrade2
Worksapce
if-else statement example
Program LetterGrade2: a better version of LetterGrade
>> LetterGrade2
Worksapce
Input your total grade Grade = 85
if-else statement example
Program LetterGrade2: a better version of LetterGrade
true
>> LetterGrade2
Worksapce
Input your total grade 85 Grade =85
grade 85
if-else statement example
Program LetterGrade2: a better version of LetterGrade
>> LetterGrade2
Worksapce
Input your total grade 85 Grade =85
grade 85
Your letter grade is P
if-else statement example
Program LetterGrade2: a better version of LetterGrade
>> LetterGrade2
Worksapce
Input your total grade 85 Grade =85
grade 85
Your letter grade is P
if-else statement example
Program LetterGrade2: a better version of LetterGrade
>> LetterGrade2
Worksapce
Input your total grade 85 grade 85
Your letter grade is P
>> LetterGrade2
if-else statement example
Program LetterGrade2: a better version of LetterGrade
>> LetterGrade2
Worksapce
Input your total grade 85 Grade =85
grade 85
Your letter grade is P
>> LetterGrade2
Input your total grade
if-else statement example
Program LetterGrade2: a better version of LetterGrade
false
>> LetterGrade2
Worksapce
Input your total grade 85 Grade =55
grade 85
Your letter grade is P
>> LetterGrade2
Input your total grade 55
if-else statement example
Program LetterGrade2:a better version of LetterGrade
skip
>> LetterGrade2
Worksapce
Input your total grade 85 Grade =55
grade 85
Your letter grade is P
>> LetterGrade2
Input your total grade 55
if-else statement example
Program LetterGrade2: a better version of LetterGrade
>> LetterGrade2
Worksapce
Input your total grade 85 Grade =55
grade 85
Your letter grade is P
>> LetterGrade2
Input your total grade 55
Your letter grade is F
if-else statement example
Program LetterGrade2: a better version of LetterGrade
What if
someone entered an invalid input (-ve grade for
example)?
or
there were more than two cases to cover (you want to
give A, B, C, D, F grades)
if-elseif statement
What if
someone entered an invalid input (-ve grade for
example)?
or
there were more than two cases to cover (you want to
give A, B, C, D, F grades)
General if syntax
if condition1 Every if statement must
consequent1 have if, condition,
elseif condition2 consequent
consequent2
else
alternate
end
General if syntax
if condition1
consequent1
elseif condition2
consequent2
else
alternate
end You can have as many elseif
parts as you need.
General if syntax
if condition1
consequent1
elseif condition2
consequent2
else The final else part is not
alternate necessary, but always a
end good idea.
General if syntax
if condition1
consequent1
elseif condition2
consequent2
else
alternate
end The end word is necessary.
Exercise 1
if (a > b & b > 3) a = 16
c = 3; b = 4
else A) 3
c = 5;
B) 4
end;
disp(c) C) 5
Exercise 2
if (a > b & b > 3) a = 3
c = 3; b = 4
else A) 3
c = 5;
B) 4
end;
disp(c) C) 5
Exercise 3
if (a > b & b > 3) a = 16
c = 3; b = 4
c = 4; A) 3
else
B) 4
c = 5;
end; C) 5
disp(c)
Exercise 4
score = 95
if (score > 55)
disp( ‘D’ ) What will this code
display
elseif (score > 65)
disp( ‘C’) A) D
elseif (score > 80) B) A
disp( ‘B’ )
C) Not good…
elseif (score > 93)
disp( ‘A’ ) What’s wrong with this
else code???
disp( ‘Not good…’ )
end
Exercise 4 - modified
score = 95
if (score > 93)
disp( ‘A’ ) What will this code
display
elseif (score > 80)
disp( ‘B’) A) D
elseif (score > 70) B) A
disp( ‘C’ )
C) Not good…
elseif (score > 60)
disp( ‘D’ )
else
disp( ‘F’ )
end
if statements and vectors
We know the following
Any Questions
SCIENTIFIC COMPUTING
LECTURE # 10
CHAPTER5 – PART3 FOR LOOPS (5.3)
for loops vs. while loops
2
In while
we ask MATLAB to execute a block of code while a certain
condition is true
In for loops
we ask MATLAB to execute a block of code for all values in a
certain vector
Usually used to execute a block of code for a certain number of
times
for loop syntax
3
How it works:
For each value in <vector>, assign the value to <variable>
and execute the <code block>
Simple for loop example
4
SimpleForLoop
>> SimpleForLoop
Workspace
index 1
Simple for loop example
5
SimpleForLoop
>> SimpleForLoop
Workspace
1 index 1
Simple for loop example
6
SimpleForLoop
>> SimpleForLoop
Workspace
1 index 2
Simple for loop example
7
SimpleForLoop
>> SimpleForLoop
Workspace
1 index 2
2
Simple for loop example
8
SimpleForLoop
>> SimpleForLoop
Workspace
1 index 3
2
Simple for loop example
9
SimpleForLoop
>> SimpleForLoop
Workspace
1 index 3
2
3
Simple for loop example
10
SimpleForLoop
>> SimpleForLoop
Workspace
1 index 4
2
3
Simple for loop example
11
SimpleForLoop
>> SimpleForLoop
Workspace
1 index 4
2
3
4
A for loop can be any of the following
12
for k= [1,3,7,8,9,11]
disp(k) k takes on the values one by one
end
for k = 2:0.5:3
disp(k) real number increment
end Values of k: 2 2.5 3
for k = 1:4 1
2
disp(k) 3
4
end
for k = 2:0.5:3 2
disp(k) 2.5000
end 3
for k = 0:-2:-7 0
-2
disp(k) -4
-6
end
14
14
Example 2:
A program used in printing flyers that reads a number n
and prints the phrase ‘Welcome Huskies’ n times
Example 2
How it works:
The <code block> is executed repetitively until the <condition>
becomes false
Simple while loop example
3
SimpleWhileLoop
>> SimpleWhileLoop
Workspace
index 1
Simple while loop example
4
SimpleWhileLoop
true
>> SimpleWhileLoop
Workspace
index 1
Simple while loop example
5
SimpleWhileLoop
>> SimpleWhileLoop
Workspace
1 index 1
Simple while loop example
6
SimpleWhileLoop
>> SimpleWhileLoop
Workspace
1 index 2
Simple while loop example
7
SimpleWhileLoop
true
>> SimpleWhileLoop
Workspace
1 index 2
Simple while loop example
8
SimpleWhileLoop
>> SimpleWhileLoop
Workspace
1 index 2
2
Simple while loop example
9
SimpleWhileLoop
>> SimpleWhileLoop
Workspace
1 index 3
2
Simple while loop example
10
SimpleWhileLoop
true
>> SimpleWhileLoop
Workspace
1 index 3
2
Simple while loop example
11
SimpleWhileLoop
>> SimpleWhileLoop
Workspace
1 index 3
2
3
Simple while loop example
12
SimpleWhileLoop
>> SimpleWhileLoop
Workspace
1 index 4
2
3
Simple while loop example
13
SimpleWhileLoop
true
>> SimpleWhileLoop
Workspace
1 index 4
2
3
Simple while loop example
14
SimpleWhileLoop
>> SimpleWhileLoop
Workspace
1 index 4
2
3
4
Simple while loop example
15
SimpleWhileLoop
>> SimpleWhileLoop
Workspace
1 index 5
2
3
4
Simple while loop example
16
SimpleWhileLoop
false
>> SimpleWhileLoop
Workspace
1 index 5
2
3
4
Simple while loop example
17
SimpleWhileLoop
exit
>> SimpleWhileLoop
Workspace
1 index 5
2
3
4
Example 2: a loop that will not end – infinite loop
18
x = 1; Output
while x ~= 10 1
x = x + 2 3
5
end 7
9
BAD situation!! 11
. . . . .
Loop will never end
Example
19
Any Questions
LECTURE 12
CELL ARRAYS AND FILE INPUT/OUTPUT
Aggregating Strings of unequal length
We can aggregate strings of unequal length in a cell array.
A cell array can hold data of non-similar types.
You reference elements in a cell array using { } instead of ( ).
Strings of unequal length are one example for that.
Cell Arrays of Strings
>> Y = {'a','bb','ccc‘};
>> MakeColumInTxt=1;
>> txt{minMilPos+1,MakeColumInTxt}
ans =
Volvo Passat
Car’s example cont.
xlsread can also return all the data in one cell array. That would be
the third output parameter; raw in the example below.
>>[num, txt, raw] = xlsread('cars.xlsx');
Car’s example cont.
>>[num, txt, raw] = xlsread('cars.xlsx');
>> raw
raw =
{'Make' 'Year' 'Cost' 'Miles' 'Accidents';
'BMW 3 Series' [2008] [20000] [ 43200] [ 2];
'Volvo Jetta' [2011] [16600] [ 31700] [ 0];
'Volvo Jetta' [2008] [10998] [102790] [ 3];
'Volvo Passat' [2012] [15000] [ 34000] [ 2];
'Volvo Passat' [2013] [20500] [ 12023] [ 0];
'Volvo Passat' [2008] [12800] [ 65200] [ 2];
'BMW X5' [2012] [52000] [ 18500] [ 0];
'BMW X5' [2011] [50000] [ 19000] [ 2];
'BMW X3' [2006] [13500] [100000] [ 0];
'BMW X3' [2009] [25000] [ 40000] [ 1]}
Writing to an Excel file
MATLAB xlswrite write data in a cell array to an Excel file.
In the car’s example, if we want to update any of the data and write
the data back to a file, the cell array for this data should look like
raw, the cell array returned by xlsread
Summary
Any program you write involves
Getting input
Processing
Generating output
Sources of input we covered
Keyboard
Excelfile
Image or sound file
Sources of output
Screen
USB port (Arduino)
Excel file
Processing
Matrix
arithmetic
MATLAB built in functions
Mathematical
Data analysis
Matrix logical indexing and find function
Plotting
Strings
28
Any Questions