Sunday, 31 July 2016

MATLAB Programming 42 - Some array functions (3)


Special Arrays in MATLAB


A Magic Square


A magic square is a square that produces the same sum, when its elements are added row-wise, column-wise or diagonally.

The magic() function creates a magic square array. 


It takes a singular argument that gives the size of the square. The argument must be a scalar greater than or equal to 3.

magic(4)

MATLAB will execute the above statement and return the following result:


ans =
16 2 3 13
5 11 10 8
9 7 6 12
4 14 15 1



MATLAB Programming 42 - Some array functions (2)


Special Arrays in MATLAB


The eye() function creates an identity matrix.


For example:


eye(4)

MATLAB will execute the above statement and return the following result:


ans =
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

The rand() function creates an array of uniformly distributed random numbers on (0,1):


For example:


rand(3, 5)

MATLAB will execute the above statement and return the following result:


ans =
0.8147  0.9134  0.2785  0.9649  0.9572
0.9058  0.6324  0.5469  0.1576  0.4854
0.1270  0.0975  0.9575  0.9706  0.8003

MATLAB Programming 42 - Some array functions (1)


Special Arrays in MATLAB


In this section, we will discuss some functions that create some special arrays. For all these functions, a single argument creates a square array, double arguments create rectangular array.

The zeros() function creates an array of all zeros:


For example:

zeros(5)

MATLAB will execute the above statement and return the following result:


ans =
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

The ones() function creates an array of all ones:


For example:

ones(4,3)

MATLAB will execute the above statement and return the following result:

ans =
1 1 1
1 1 1
1 1 1
1 1 1

MATLAB Programming 41 - Some vector operations (9)


Vectors with Uniformly Spaced Elements


MATLAB allows you to create a vector with uniformly spaced elements.

To create a vector v with the first element f, last element l, and the difference between elements is any real number n, we write:


v = [f : n : l]

Example


Create a script file with the following code:


v = [1: 2: 20];
sqv = v.^2;
disp(v);disp(sqv);


When you run the file, it displays the following result:


1 3 5 7 9 11 13 15 17 19
1 9 25 49 81 121 169 225 289 361

MATLAB Programming 41 - Some vector operations (8)

Vector Dot Product


Dot product of two vectors a = (a1, a2, …, an) and b = (b1, b2, …, bn) is given by:


a.b = Σ(ai.bi)

Dot product of two vectors a and b is calculated using the dot function.


dot(a, b);

Example


Create a script file with the following code:


v1 = [2 3 4];
v2 = [1 2 3];
dp = dot(v1, v2);
disp('Dot Product:'); disp(dp);


When you run the file, it displays the following result:


Dot Product:
20

MATLAB Programming 41 - Some vector operations (7) (Example)

Example


Create a script file with the following code:


v = [1: 2: 20];
sv = v.* v; %the vector with elements
% as square of v's elements
dp = sum(sv); % sum of squares -- the dot product
mag = sqrt(dp); % magnitude
disp('Magnitude:'); disp(mag);


When you run the file, it displays the following result:


Magnitude:
36.4692

MATLAB Programming 41 - Some vector operations (7)

Magnitude of a Vector


Magnitude of a vector v with elements v1, v2, v3, …, vn, is given by the equation:


|v| = √(v12 + v22 + v32 + … + vn2)

You need to take the following steps to calculate the magnitude of a vector:


Take the product of the vector with itself, using array multiplication (.*). This produces a vector sv, whose elements are squares of the elements of vector v.


sv = v.*v;

Use the sum function to get the sum of squares of elements of vector v. This is also called the dot product of vector v.


dp= sum(sv);

Use the sqrt function to get the square root of the sum which is also the magnitude of the vector v.


mag = sqrt(s);


MATLAB Programming 41 - Some vector operations (6) (Example)

Example


Create a script file with the following code:


r1 = [ 1 2 3 4 ];
r2 = [5 6 7 8 ];
r = [r1,r2]
rMat = [r1;r2]
c1 = [ 1; 2; 3; 4 ];
c2 = [5; 6; 7; 8 ];
c = [c1; c2]
cMat = [c1,c2]

When you run the file, it displays the following result:


r =
1 2 3 4 5 6 7 8

rMat =
1 2 3 4
5 6 7 8

c =
1
2
3
4
5
6
7
8

cMat =
1 5
2 6
3 7
4 8


MATLAB Programming 41 - Some vector operations (6)

Appending Vectors


MATLAB allows you to append vectors together to create new vectors.

If you have two row vectors r1 and r2 with n and m number of elements, to create a row vector r of n plus m elements, by appending these vectors, you write:


r = [r1,r2]

You can also create a matrix r by appending these two vectors, the vector r2, will be the second row of the matrix:


r = [r1;r2]

However, to do this, both the vectors should have same number of elements.

Similarly, you can append two column vectors c1 and c2 with n and m number of elements. To create a column vector c of n plus m elements, by appending these vectors, you write:


c = [c1; c2]

You can also create a matrix c by appending these two vectors; the vector c2 will be the second column of the matrix:

c = [c1, c2]


However, to do this, both the vectors should have same number of elements.



MATLAB Programming 41 - Some vector operations (5)

Transpose of a Vector


The transpose operation changes a column vector into a row vector and vice versa. The transpose operation is represented by a single quote (').


Example


Create a script file with the following code:


r = [ 1 2 3 4 ];
tr = r';
v = [1;2;3;4];
tv = v';
disp(tr); disp(tv);


When you run the file, it displays the following result:


1
2
3
4
1 2 3 4


MATLAB Programming 41 - Some vector operations (4)

Scalar Multiplication of Vectors


When you multiply a vector by a number, this is called the scalar multiplication. Scalar multiplication produces a new vector of same type with each element of the original vector multiplied by the number.

Example


Create a script file with the following code:


v = [ 12 34 10 8];
m = 5 * v

When you run the file, it displays the following result:


m =
60 170 50 40

Please note that you can perform all scalar operations on vectors. For example, you can add, subtract and divide a vector with a scalar quantity.


MATLAB Programming 41 - Some vector operations (3)

Addition and Subtraction of Vectors


You can add or subtract two vectors. Both the operand vectors must be of same type and have same number of elements.


Example


Create a script file with the following code:


A = [7, 11, 15, 23, 9];
B = [2, 5, 13, 16, 20];
C = A + B;
D = A - B;
disp(C);
disp(D);

When you run the file, it displays the following result:


9 16 28 39 29
5 6 2 7 -11


MATLAB Programming 41 - Some vector operations (2)

Referencing the Elements of a Vector


You can reference one or more of the elements of a vector in several ways. The ith component of a vector v is referred as v(i).

For example:


v = [ 1; 2; 3; 4; 5; 6]; % creating a column vector of 6 elements

v(3)

MATLAB will execute the above statement and return the following result:


ans =
3

When you reference a vector with a colon, such as v(:), all the components of the vector are listed.


v = [ 1; 2; 3; 4; 5; 6]; % creating a column vector of 6 elements

v(:)


MATLAB will execute the above statement and return the following result:


ans =
1
2
3
4
5
6

MATLAB allows you to select a range of elements from a vector.

For example, let us create a row vector rv of 9 elements, then we will reference the elements 3 to 7 by writing rv(3:7) and create a new vector named sub_rv.


rv = [1 2 3 4 5 6 7 8 9];
sub_rv = rv(3:7)

MATLAB will execute the above statement and return the following result:


sub_rv =

3 4 5 6 7



MATLAB Programming 41 - Some vector operations

A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors:

Row vectors
Column vectors

Row Vectors


Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements.

r = [7 8 9 10 11]

MATLAB will execute the above statement and return the following result:

r =
Columns 1 through 4
7 8 9 10
Column 5
11

Column Vectors


Column vectors are created by enclosing the set of elements in square brackets, using semicolon to delimit the elements.

c = [7; 8; 9; 10; 11]

MATLAB will execute the above statement and return the following result:

c =
7
8
9
10
11


MATLAB Programming 40 - continue statement in while loop (Example)

Example


Create a script file and type the following code:


a = 10;

while a < 20

     if a == 15     

     a = a + 1;

     continue;

     end

fprintf('value of a: %d\n', a);

a = a + 1;

end


When you run the file, it displays the following result:


value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 16

value of a: 17

value of a: 18

value of a: 19

MATLAB Programming 40 - continue statement in while loop

The continue Statement


The continue statement is used for passing control to next iteration of for or while loop.

The continue statement in MATLAB works somewhat like the break statement. Instead of forcing termination, however, 'continue' forces the next iteration of the loop to take place, skipping any code in between.


Friday, 29 July 2016

MATLAB Programming 39 - break statement in while loop

Example


Create a script file and type the following code:

a = 10;

% while loop execution
while (a < 20 )

     fprintf('value of a: %d\n', a);

     a = a+1;

     if( a > 15)

     % terminate the loop using break statement
     break;

     end

end

When you run the file, it displays the following result:


value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15


MATLAB Programming 38 - break statement in for loop

The break Statement


The break statement terminates execution of for or while loop. Statements in the loop that appear after the break statement are not executed.


In nested loops, break exits only from the loop in which it occurs. Control passes to the statement following the end of that loop.




MATLAB Programming 38 - Loop Control Statements

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

MATLAB supports the following control statements. Click the following links to check their detail.

break statement - Terminates the loop statement and transfers execution to the statement immediately following the loop.

continue statement - Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

Thursday, 28 July 2016

MATLAB Programming 37 - nesting of loops (Example)

Example


Let us use a nested for loop to display all the prime numbers from 1 to 100.

Create a script file and type the following code:


for i=2:100
     for j=2:100
          if(~mod(i,j))
          break; % if factor found, not prime
          end
     end
     if(j > (i/j))
          fprintf('%d is prime\n', i);
     end
end


When you run the file, it displays the following result:


2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime

MATLAB Programming 37 - nesting of loops

The Nested Loops


MATLAB allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.

Syntax


The syntax for a nested for loop statement in MATLAB is as follows:


for m = 1:j
     for n = 1:k
          <statements>;
     end
end


The syntax for a nested while loop statement in MATLAB is as follows:


while <expression1>
     while <expression2>
          <statements>
     end
end


MATLAB Programming 36 - for loop (Example)

Example 3


Create a script file and type the following code:


for a = [24,18,17,23,28]
     disp(a)
end

When you run the file, it displays the following result:


24
18
17
23
28

MATLAB Programming 36 - for loop (Example)

Example 2


Create a script file and type the following code:


for a = 1.0: -0.1: 0.0
     disp(a)
end


When you run the file, it displays the following result:


1
0.9000
0.8000
0.7000
0.6000
0.5000
0.4000
0.3000
0.2000
0.1000

MATLAB Programming 36 - for loop (Example)

Example 1


Create a script file and type the following code:


for a = 10:20
fprintf('value of a: %d\n', a);
end

When you run the file, it displays the following result:


value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

MATLAB Programming 36 - for loop

The for Loop


A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax


The syntax of a for loop in MATLAB is:


for index = values
     <program statements>
             ...
end

values has one of the following forms:


initval:endval - increments the index variable from initval to endval by 1, and repeats execution of program statements until index is greater than endval.

initval:step:endval - increments index by the value step on each iteration, or decrements when step is negative.

valArray - creates a column vector index from subsequent columns of arrayvalArray on each iteration. For example, on the first iteration, index = valArray(:,1). The loop executes for a maximum of n times, where n is the number of columns of valArray, given by numel(valArray, 1, :). The input valArray can be of any MATLAB data type, including a string, cell array, or struct.





Wednesday, 27 July 2016

MATLAB Programming 35 - while loop (Example)

Example


Create a script file and type the following code:


a = 10;
% while loop execution
while( a < 20 )
     fprintf('value of a: %d\n', a);
     a = a + 1;
end


When you run the file, it displays the following result:


value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

MATLAB Programming 35 - while loop

The while Loop


The while loop repeatedly executes statements while condition is true.

Syntax


The syntax of a while loop in MATLAB is:

while <expression>
       <statements>
end

The while loop repeatedly executes program statement(s) as long as the expression remains true.

An expression is true when the result is nonempty and contains all nonzero elements (logical or real numeric). Otherwise, the expression is false.


Thursday, 21 July 2016

MATLAB Programming 34 - nested switch case statement (Example)

Example


Create a script file and type the following code in it:


a = 100;

b = 200;

switch(a)

case 100

fprintf('This is part of outer switch %d\n', a );

switch(b)

case 200

fprintf('This is part of inner switch %d\n', a );

end

end

fprintf('Exact value of a is : %d\n', a );

fprintf('Exact value of b is : %d\n', b );

When you run the file, it displays:


This is part of outer switch 100

This is part of inner switch 100

Exact value of a is : 100

Exact value of b is : 200

MATLAB Programming 34 - nested switch case statement

The Nested Switch Statements


It is possible to have a switch as part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.

Syntax


The syntax for a nested switch statement is as follows:


switch(ch1)

case 'A'

fprintf('This A is part of outer switch');

switch(ch2)

case 'A'

fprintf('This A is part of inner switch' );

case 'B'

fprintf('This B is part of inner switch' );

end

case 'B'

fprintf('This B is part of outer switch' );

end



MATLAB Programming 33 - switch case statement (Example)

Example


Create a script file and type the following code in it:


grade = 'B';

switch(grade)

case 'A'

fprintf('Excellent!\n' );

case 'B'

fprintf('Well done\n' );

case 'C'

fprintf('Well done\n' );

case 'D'

fprintf('You passed\n' );

case 'F'

fprintf('Better try again\n' );

otherwise

fprintf('Invalid grade\n' );

end


When you run the file, it displays:



Well done

Your grade is B

MATLAB Programming 33 - switch case statement

The switch Statement


A switch block conditionally executes one set of statements from several choices. Each choice is covered by a case statement.

An evaluated switch_expression is a scalar or string.

An evaluated case_expression is a scalar, a string or a cell array of scalars or strings.

The switch block tests each case until one of the cases is true. A case is true when:

For numbers, eq(case_expression,switch_expression).

For strings, strcmp(case_expression,switch_expression).

For objects that support the eq function,eq(case_expression,switch_expression).

For a cell array case_expression, at least one of the elements of the cell array matches switch_expression, as defined above for numbers, strings and objects.

When a case is true, MATLAB executes the corresponding statements and then exits the switch block.

The otherwise block is optional and executes only when no case is true.


Syntax


The syntax of switch statement in MATLAB is:


switch <switch_expression>
case <case_expression>
<statements>
case <case_expression>
<statements>
...
...
otherwise
<statements>
end



MATLAB Programming 32 - nested if statement (Example)

Example


Create a script file and type the following code in it:


a = 100;

b = 200;

% check the boolean condition

if( a == 100 )

% if condition is true then check the following

if( b == 200 )

% if condition is true then print the following

fprintf('Value of a is 100 and b is 200\n' );

end

end

fprintf('Exact value of a is : %d\n', a );

fprintf('Exact value of b is : %d\n', b );


When you run the file, it displays:


Value of a is 100 and b is 200

Exact value of a is : 100

Exact value of b is : 200

MATLAB Programming 32 - nested if statement

The Nested if Statements

It is always legal in MATLAB to nest if-else statements which means you can use one if or elseif statement inside another if or elseif statement(s).

Syntax

The syntax for a nested if statement is as follows:

if <expression 1>

% Executes when the boolean expression 1 is true

if <expression 2>

% Executes when the boolean expression 2 is true

end

end

You can nest elseif...else in the similar way as you have nested if statement.


MATLAB Programming 31 - if...elseif...elseif...else statement (Example)

Example

Create a script file and type the following code in it:

a = 100;

%check the boolean condition

if a == 10

% if condition is true then print the following

fprintf('Value of a is 10\n' );
elseif( a == 20 )

% if else if condition is true

fprintf('Value of a is 20\n' );
elseif a == 30

% if else if condition is true

fprintf('Value of a is 30\n' );
else

% if none of the conditions is true '

fprintf('None of the values are matching\n');
fprintf('Exact value of a is: %d\n', a );
end


When the above code is compiled and executed, it produces the following result:


None of the values are matching
Exact value of a is: 100

MATLAB Programming 31 - if...elseif...elseif...else statement


if...elseif...elseif...else...end Statements


An if statement can be followed by one (or more) optional elseif... and an else statement, which is very useful to test various conditions.

When using if... elseif...else statements, there are few points to keep in mind:


An if can have zero or one else's and it must come after any elseif's.
An if can have zero to many elseif's and they must come before the else.
Once an else if succeeds, none of the remaining elseif's or else's will be tested.

Syntax


if <expression 1>          % Executes when the expression 1 is true
<statement(s)>
elseif <expression 2>    % Executes when the boolean expression 2 is true
<statement(s)>
Elseif <expression 3>   
% Executes when the boolean expression 3 is true
<statement(s)>
else                                
% executes when the none of the above condition is true
<statement(s)>
end