0% found this document useful (0 votes)
22 views19 pages

Rob Lab 2

This document provides an introduction to vectors and matrices in MATLAB, covering their definition, creation, and manipulation. It explains how to access elements within vectors and matrices, as well as the use of control statements like if, switch, and loops for programming tasks. Additionally, it includes practical examples and commands to facilitate understanding of MATLAB's functionality.

Uploaded by

Wajeeh Ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views19 pages

Rob Lab 2

This document provides an introduction to vectors and matrices in MATLAB, covering their definition, creation, and manipulation. It explains how to access elements within vectors and matrices, as well as the use of control statements like if, switch, and loops for programming tasks. Additionally, it includes practical examples and commands to facilitate understanding of MATLAB's functionality.

Uploaded by

Wajeeh Ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Introduction to Vectors in MATLAB

This is the basic introduction to MATLAB. Creation of vectors includes a few basic operations.
Topics include the following:
 Defining a vector
 Accessing elements within a vector

Defining a Vector

MATLAB is a software package that makes it easier for you to enter matrices and vectors to
manipulate them. The interface follows a language that is designed to look a lot like the notation
used in linear algebra.
Almost all of MATLAB 's basic commands revolve around the use of vectors. A vector is defined by
placing a sequence of numbers within square braces:

>> v = [3 1 7 -21 5 6 4]

v=
3 1 7 -21 5 6 4

This creates a row vector which has the label "v". The first entry in the vector is a 3 and the second
entry is a 1. Note that MATLAB printed out a copy of the vector after you hit the enter key. If you do
not want to print out the result, put a semi-colon at the end of the line:

>> v = [3 1 7 -21 5 6 4];

If you want to view the vector just type its label:

>> v
v=
3 1 7 -21 5 6 4

1
Notice, though, that this always creates a row vector. If you want to create a column vector you
need to take the transpose of a row vector. The transpose is defined using an apostrophe (`):

>> v = [3 1 7 -21 5 6 4]'


v=
3
1
7
-21
5
6
4
Or you can use the transpose operator ( .’ )
>> w=v.’
w= 3
1
7
-21
5
6
4

To access block of elements, we use MATLAB’s colons notation, e.g. to access the first three
elements of v we write.
>> v (1:3)
ans =
3 1 7

Similarly, to access the second through fourth elements of v we write


>> v (2:4)
ans =

1 7 -21

Similarly, to access all elements from some specific location say the 3rd through the last element.

>> v (3: end)


ans =
7 -21 5 6 4

2
>> v (:)
Produces a column vector.

>> v (1: end)


Produces a row vector.

Indexing is not restricted to contiguous elements.

>> v (1:2: end)


ans =
3 7 5 4

>> v (end: -2:1)


ans =
4 5 7 3

A common task is to create a large vector with numbers that fit a repetitive pattern. MATLAB can
define a set of numbers with a common increment using colons. For example, to define a vector
whose first entry is 1, the second entry is 2, the third is three, up to 8 you enter the following:

>> v = [1:8]
v=
1 2 3 4 5 6 7 8

If you wish to use an increment other than one, you have to define the start number, the value of the
increment, and the last number. For example, to define a vector that starts with 2 and ends in 4 with
steps of .25 you enter the following:

>> v = [2:.25:4]
v=
Columns 1 through 7
2.0000 2.2500 2.5000 2.7500 3.0000 3.2500 3.5000
Columns 8 through 9
3.7500 4.0000

Accessing elements within a vector

You can view individual entries in this vector. For example, to view the first entry just type in the
following:

>> v(1)

3
ans =
2

This command prints out entry 1 in the vector. Also notice that a new variable called ANS has been
created. Any time you perform an action that does not include an assignment MATLAB will put the
label ANS on the result.

A vector can be used as an index into another vector. For example, we can pick the first, third sixth
and seventh elements of v using the command.

>> v ([1 3 6 7])


v=
3 7 6 4
Class Practical:
 Its better to do in editor window as it will help understand and make the text
modifiable if something went wrong than directly applying in command windows.
 For this purpose lets first save the file then gets started.

4
To check whether file is saved or not either you can visit the folder where you saved or from
the file name being changed from untitled to the name you saved as in above screenshot it
got changed to “Lab2” it means our file is not saved and we can continue.
 One more thing as I am using same file for the whole lab so I will comment the code
which has been executed so that it doesn’t create mess. Commenting out a line of
code in MATLAB is done by just placing “%” sign and you will see it often in
screenshot from now ahead.
Creating a Row Vector:
Before that one more thing when you run the MATLAB code it should have the same path
as the folder in which it is saved so just click on change folder or add to path manually, I
prefer clicking Change Folder and it automatically adjust it.

Result:

On Command Window you can see the result both variable and its value are being displayed

5
if you had placed a semicolon at end of line it would have just created a variable without
showing in command window. For that in command window you would’ve had to call the
variable yourself.

Now when you call it as “a” in command window you will then only see the value of
variable named “a”.

Creating a Column Vector:


You can use apostrophe at previous vector, and it will become column vector or use
semicolon between each entry inside the variable value in vector.
 By Apostrophe:

6
 By Semicolons:

Accessing Values from within Vector:

7
a(1:2) will pick the first 2 entries of this column vector. For picking last 3 values you can
use end statement as shown below.

You could have just used 5 instead of end but in large vectors it would have been hard to
deal with and there it comes into play in following form like:

End-2 position will take you to 3rd last entry.

8
Introduction to Matrices in MATLAB

A basic introduction to defining and manipulating matrices is given here. It is assumed that you know
the basics on how to define and manipulate vectors using MATLAB.

Defining Matrices

Defining a matrix is similar to defining a vector. To define a matrix, you can treat it like a column of
row vectors (note that the spaces are required!):

>> A = [1 2 3; 3 4 5; 6 7 8]

A=
1 2 3
3 4 5
6 7 8

You can also treat it like a row of column vectors:

>> B = [ [1 2 3]' [2 4 7]' [3 5 8]']


B=

1 2 3
2 4 5
3If you 7have 8been putting in variables through this and the tutorial on vectors, then you probably have
a lot of variables defined. If you lose track of what variables you have defined, the WHOS command
will let you know all of the variables you have in your workspace.

>>
whos
Name Size Bytes Class
A 3x3 72 double array
B 3x3 72 double array
v 1x5 40 double array
The grand total is 23 elements using 184 bytes.

You can work with different parts of a matrix, just as you can with vectors. Again, you have to be
careful to make sure that the operation is legal.

To extract the element in the 2nd row and 3rd column we write,
>> A (2,3)

9
ans =
5
The colon operator is used in the matrix indexing to select a two-dimensional block of elements out
of matrix:
>> C= A (: , 3) % this statement picks the third column of the
matrix C =
3
5
8

The colon operator can also be used in the matrix indexing to extract the row of the matrix

>> C= A (2, :) % this statement picks the 2nd row of the


matrix C =
4 5

>> A (1:2,2:3)
ans =
2 3
4 5

>> ans’
ans =
2 4
3 5

To create a matrix B equal to A but with its last column set to 0’s we write
>> B = A;
>> B (:, 3) = 0
B=
1 2 0
2 4 0
3 7 0
>> A (end, end)
ans =
8

>> D = A ([1 3], [2 3])


D=

10
2 3
7 8

Matrix addressing can also be used in the following way


>> E = logical ([1 0 0; 0 0 1; 0 0 0])
E=
1 0 0
0 0 1
0 0 0

Now if we write.
>> A(E)
ans =
1
5

The use of a colon is useful in finding the sum of all elements of a matrix.
>> s = sum (A (:))
s=
3
9

Some important standard arrays are:

For example,
>> A = 5 * ones (3, 3)
A=
5 5 5
5 5 5
5 5 5

>> magic (3)


ans =
8 1 6
3 5 7
4 9 2

Finally, sometimes you would like to clear all your data and start over. You do this with the "clear"
command. Be careful though, it does not ask you for a second opinion and its results are final.

11
>> clear
Up till now we have been using vectors but for matrix you can use combination of ; and , or
a space for creating a row and column value respectively.

Rest of the above operations can be done as er of vectors here also:


Sum, subtract etc. all algebraic functions take account the knowledge of matrices.

Rest of the functions are above discussed in the manual already.

Conditional control (If, Switch)

This group of control statements enables you to select at run-time which block of code is executed. To

12
make this selection based on whether a condition is true or false, use the ‘ if’ statement (which may
include else or elseif). To select from a number of possible options depending on the value of an
expression, use the switch and case statements.

if, else, and elseif

if evaluates a logical expression and executes a group of statements based on the value of the expression.
In its simplest form, its syntax is

if logical_expression
statements
end

If the logical expression is true (1), MATLAB executes all the statements between the if and end
lines. It resumes execution at the line following the end statement. If the condition is false (0),
MATLAB skips all the statements between the if and end lines and resumes execution at the line
following the end statement.

For example,
if rem(a, 2) == 0
disp('a is
even') b = a/2;
end
You can nest any number of if statements.

switch, case, and otherwise.

Switch executes certain statements based on the value of a variable or expression. Its basic form is
switch expression (scalar or string)

case value1

statements % Executes if expression is value1


case value2
statements % Executes if expression is value2
.
.
.
otherwise
statements % Executes if expression does not

13
% match any case
End

This block consists of


 The word switch followed by an expression to evaluate.
 Any number of case groups. These groups consist of the word case followed by a possible
value for the expression, all on a single line. Subsequent lines contain the statements to execute
for the given value of the expression. These can be any valid MATLAB statement including
another switch block. Execution of a case group ends when MATLAB encounters the next case
statement or the otherwise statement. Only the first matching case is executed.
 An optional otherwise group. This consists of the word otherwise, followed by the statements
to execute if the expression's value is not handled by any of the preceding case groups.
Execution of the otherwise group ends at the end statement.
 An end statements.
Class Example:
Lets create a command to check in which section of UET Batch 2k21 you come for this we
can use the following command, in addition to if else we are using input command for
storing value inside variable which will then be cross checked and in whatever if else
statement it lies it will print out that section else move forward:

We can use ‘clc’ program for cleaning command window and clear all; in editor code so that
it clears all previous variables if any before variable value exists.

14
Let’s run the command:

It asks for roll number for ease lets enter my roll number and check to which section I belong:

15
As expected it gave me result of Section B which is actually my section.

Loops

With loop control statements, you can repeatedly execute a block of code, looping back through
the block while keeping track of each iteration with an incrementing index variable. Use the “for
statement” to loop a specific number of times.

For Loop

The for loop executes a statement or group of statements a predetermined number of times.
Its syntax is
for index = initial: increment: final
statements
end

The default increment is 1. You can specify any increment, including a negative one. For positive
indices, execution terminates when the value of the index exceeds the end value; for negative
increments, it terminates when the index is less than the end value.

For example, this loop executes five times.

for n = 2:6
x(n) = 2 * x(n - 1);
end

You can nest multiple for loops.

for m = 1:5
for n = 1:100
A(m, n) = 1/(m + n - 1);
end
end

while Loop

The while loop executes a statement or group of statements repeatedly as long as the controlling
expression is true (1).

Its syntax is
while expression

16
statements
end

If the expression evaluates to a matrix, all its elements must be 1 for execution to continue. To
reduce a matrix to a scalar value, use all and any functions.

For example, this while loop finds the first integer n for which n! (n factorial) is a 100-digit number.
And n = 1.

while prod(1:n) <


1e100 n = n + 1;
end

Exit a while loop at any time using the break statement.

Continue

The continue statement passes control to the next iteration of the ‘for’ or ‘while’ loop in which it
appears, skipping any remaining statements in the body of the loop. The example below shows a
continue loop that counts the lines of code in the file, skipping all blank lines and comments.

fid = fopen('magic.m', 'r');


count = 0;
while ~feof(fid) line = fgetl(fid);
if isempty(line) | strncmp(line, '%', 1)
continue
end
count = count +
1; end
disp(sprintf('%d lines', count));

Break

The break statement terminates the execution of a “for loop” or while loop. When a break statement
is encountered, execution continues with the next statement outside of the loop. In nested loops,
break exits from the innermost loop only.
The example below shows a while loop that reads the contents of the file fft.m into a MATLAB
character array. A break statement is used to exit the while loop when the first empty line is
encountered.

The resulting character array contains the M-file help for the fft program.
fid = fopen('fft.m', 'r');

17
s = '';
while ~feof(fid) line =
fgetl(fid); if isempty(line)
brea
k end
s = strvcat(s,
line); end
disp(s)

Task:

Write a MATLAB code of Factorial Program with the help of loop Constructs (Use For or While).

MATLAB CODE:

n=5;
factorial = 1;
for I = 1:1:n
factorial = factorial*i;
end
Class Example of For Loop:

For Loop:

18
Class Example of While Loop:

Logic:
For Loop

 The loop initializes the loop variable a to 1.


 It then iterates over the range 1:100, incrementing a by 1 in each iteration until a
reaches 100.
 Within each iteration, the value of a is added to the sum.

While Loop

 The loop initializes the loop variable a to 1 and sum to 0.


 The loop continues to execute as long as the condition a <= 100 is true.
 Within each iteration, the value of a is added to the sum .
 Additionally, a is incremented by 1 in each iteration ( a = a + 1), ensuring that the
loop will terminate after 100 iterations.

19

You might also like