Tuesday, 9 August 2016

Calculus using MATLAB 12 - factorization of an expression


Factorization of Algebraic Expressions


The factor function factorizes an expression. The following example demonstrates the concept:

Example


Create a script file and type the following code:


syms x
syms y
factor(x^3 - y^3)
factor([x^2-y^2,x^3+y^3])

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


ans =
(x - y)*(x^2 + x*y + y^2)

ans =
[ (x - y)*(x + y), (x + y)*(x^2 - x*y + y^2)]


Monday, 8 August 2016

Calculus using MATLAB 11 - expanding and collecting of expressions in Octave


Expanding and Collecting Equations in Octave


You need to have symbolic package, which provides expand and collect command to expand and collect an equation, respectively. The following example demonstrates the concepts:

When you work with many symbolic functions, you should declare that your variables are symbolic but Octave has different approach to define symbolic variables. Notice the use of Sin and Cos which are also defined in symbolic package.

Create a script file and type the following code:


% first of all load the package, make sure it’s installed.

pkg load symbolic

% make symbols module available

symbols

% define symbolic variables
x = sym ('x');
y = sym ('y');
z = sym ('z');

% expanding equations
expand((x-5)*(x+9))
expand((x+2)*(x-3)*(x-5)*(x+7))
expand(Sin(2*x))
expand(Cos(x+y))

% collecting equations
collect(x^3 *(x-7), z)
collect(x^4*(x-3)*(x-5), z)

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


ans =
-45.0+x^2+(4.0)*x

ans =
210.0+x^4-(43.0)*x^2+x^3+(23.0)*x

ans =
sin((2.0)*x)

ans =
cos(y+x)

ans =
x^(3.0)*(-7.0+x)

ans =
(-3.0+x)*x^(4.0)*(-5.0+x)


Calculus using MATLAB 11 - expanding and collecting of expressions


Expanding and Collecting Equations in MATLAB


The expand and the collect commands expands and collects an equation respectively. The following example demonstrates the concepts:

When you work with many symbolic functions, you should declare that your variables are symbolic.

Create a script file and type the following code:


syms x      %symbolic variable x
syms y      %symbolic variable x

% expanding equations
expand((x-5)*(x+9))
expand((x+2)*(x-3)*(x-5)*(x+7))
expand(sin(2*x))
expand(cos(x+y))

% collecting equations
collect(x^3 *(x-7))
collect(x^4*(x-3)*(x-5))

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


ans =
x^2 + 4*x - 45

ans =
x^4 + x^3 - 43*x^2 + 23*x + 210

ans =
2*cos(x)*sin(x)

ans =
cos(x)*cos(y) - sin(x)*sin(y)

ans =
x^4 - 7*x^3

ans =
x^6 - 8*x^5 + 15*x^4



Sunday, 7 August 2016

MATLAB Programming 52 - 3D plots of functions


Three-Dimensional Plots


Three-dimensional plots basically display a surface defined by a function in two variables, g = f (x,y).
As before, to define g, we first create a set of (x,y) points over the domain of the function using the meshgrid command. Next, we assign the function itself. Finally, we use the surf command to create a surface plot.

The following example demonstrates the concept:


Use the peaks function to define XY, and Z as 25-by-25 matrices. Then, create a surface plot.



[X,Y,Z] = peaks(25);

figure
surf(X,Y,Z);


surf creates the surface plot from corresponding values in XY, and Z. If you do not define the color data C, then surf uses Z to determine the color, so color is proportional to surface height.




Friday, 5 August 2016

MATLAB Programming 51 - how to draw contour


A contour line of a function of two variables is a curve along which the function has a constant value. Contour lines are used for creating contour maps by joining points of equal elevation above a given level, such as mean sea level.

MATLAB provides a contour function for drawing contour maps.

Example


Let us generate a contour map that shows the contour lines for a given function g = f(x, y). This function has two variables. So, we will have to generate two independent variables, i.e., two data sets x and y. This is done by calling the meshgrid command.

The meshgrid command is used for generating a matrix of elements that give the range over x and y along with the specification of increment in each case.


Use the meshgrid function to generate matrices X and Y. Create a third matrix, Z, and plot its contours.



x = linspace(-2*pi,2*pi);
y = linspace(0,4*pi);
[X,Y] = meshgrid(x,y);
Z = sin(X)+cos(Y);

figure
contour(X,Y,Z)




MATLAB Programming 50 - bar charts (Example)

Set the bar interior color and outline color using RGB triplets. Set the width of the bar outline



y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(y,'FaceColor',[0 .5 .5],'EdgeColor',[0 .9 .9],'LineWidth',1.5)


Create a bar graph with a three-column matrix input and return the three bar series objects. bar creates one bar series for each column in the matrix.


y = [2 4 6; 3 4 5];
b = bar(y);


Change properties for a specific bar series by indexing into the object array. For example, change properties of the bars representing the second column of y using b(2). Starting in R2014b, you can use dot notation to set properties. If you are using an earlier release, use the set function instead.


b(2).LineWidth = 2;
b(2).EdgeColor = 'red';




MATLAB Programming 50 - bar charts (Example)

Display one bar for each row of the matrix. The height of each bar is the sum of the elements in the row.



y = [2 2 3; 2 5 6; 2 8 9; 2 11 12];
bar(y,'stacked')



Create a figure with two subplots. In the upper subplot, plot a bar graph. In the lower subplot, plot a stacked bar graph of the same data.


y = [1 2 3; 4 5 6];
ax1 = subplot(2,1,1);
bar(ax1,y)

ax2 = subplot(2,1,2);
bar(ax2,y,'stacked')


Create a bar graph using red bars


y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(y,'r')




MATLAB Programming 50 - bar charts (Example)

Specify the bar locations along the x-axis


x = 1900:10:2000;
y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(x,y)


Set the width of each bar to 40 percent of the total space available for each bar.


y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(y,0.4)




Display four groups of three bars


y = [2 2 3; 2 5 6; 2 8 9; 2 11 12];
bar(y)




MATLAB Programming 50 - bar charts


Drawing Bar Charts


The bar command draws a two dimensional bar chart. Let us take up an example to demonstrate the idea.

Example


Let us have an imaginary classroom with 10 students. We know the percent of marks obtained by these students are 75, 58, 90, 87, 50, 85, 92, 75, 60 and 95. We will draw the bar chart for this data.


Create a script file and type the following code:


y = [75 91 105 123.5 131 150 179 203 226 249 281.5];
bar(y)


When you run the file, MATLAB displays the following bar chart:





Thursday, 4 August 2016

MATLAB Programming 49 - adding some functionality to graph (3)


Setting Colors on Graph


MATLAB provides eight basic color options for drawing graphs. The following table shows the colors and their codes:

w- White
k - Black
b - Blue
r - Red
c - Cyan
g - Green
m - Magenta
y - Yellow

Example


Plot three sine curves with a small phase shift between each line. Use a green line with no markers for the first sine curve. Use a blue dashed line with circle markers for the second sine curve. Use only cyan star markers for the third sine curve.



x = 0:pi/10:2*pi;
y1 = sin(x);
y2 = sin(x-0.25);
y3 = sin(x-0.5);

figure
plot(x,y1,'g',x,y2,'b--o',x,y3,'c*')




MATLAB Programming 49 - adding some functionality to graph (2)


Drawing Multiple Functions on the Same Graph


You can draw multiple graphs on the same plot. The following example demonstrates the concept:

Example


Create a script file and type the following code:


Define x as 100 linearly spaced values between $-2\pi$ and $2\pi$. Define y1 and y2 as sine and cosine values of x. Create a line plot of both sets of data.

x = linspace(-2*pi,2*pi);
y1 = sin(x);
y2 = cos(x);

figure
plot(x,y1,x,y2)


MATLAB Programming 49 - adding some functionality to graph (1)


Adding Title, Labels, Grid Lines, and Scaling on the Graph


MATLAB allows you to add title, labels along the x-axis and y-axis, grid lines and also to adjust the axes to spruce up the graph.

The xlabel and ylabel commands generate labels along x-axis and y-axis.

The title command allows you to put a title on the graph.

The grid on command allows you to put the grid lines on the graph.

The axis equal command allows generating the plot with the same scale factors and the spaces on
both axes.

The axis square command generates a square plot.



MATLAB Programming 48 - plot a graph


To plot the graph of a function, you need to take the following steps:


Define x, by specifying the range of values for the variable x, for which the function is to be plotted

Define the function, y = f(x)

Call the plot command, as plot(x, y)

Following example would demonstrate the concept.

Let us plot the simple function y = x for the range of values for x from 0 to 100, with an increment of 5.


Create a script file and type the following code:


x = [0:5:100];
y = x;
plot(x, y)

When you run the file, MATLAB displays the following plot:







Wednesday, 3 August 2016

MATLAB Programming 47 - comparison two strings


Comparing Strings


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


str1 = 'This is test'
str2 = 'This is text'
if (strcmp(str1, str2))
sprintf('%s and %s are equal', str1, str2)
else
sprintf('%s and %s are not equal', str1, str2)
end

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


str1 =
This is test
str2 =
This is text
ans =
This is test and This is text are not equal


MATLAB Programming 46 - Array functions for flipping & rotations


Array Functions


MATLAB provides the following functions to sort, rotate, permute, reshape, or shift array contents. 


length - Length of vector or largest array dimension

ndims - Number of array dimensions

numel - Number of array elements

size - Array dimensions

iscolumn - Determines whether input is column vector

isempty - Determines whether array is empty

ismatrix - Determines whether input is matrix

isrow - Determines whether input is row vector

isscalar - Determines whether input is scalar

isvctore- Determines whether input is vector

blkdiag - Constructs block diagonal matrix from input arguments

circshift - Shifts array circularly

ctranspose - Complex conjugate transpose

diag - Diagonal matrices and diagonals of matrix

flipdim - Flips array along specified dimension

fliplr - Flips matrix from left to right

flipud - Flips matrix up to down

ipermute - Inverses permute dimensions of N-D array

permute - Rearranges dimensions of N-D array

repmat - Replicates and tile array

reshape - Reshapes array

rot90 - Rotates matrix 90 degrees

shiftdim - Shifts dimensions

issorted - Determines whether set elements are in sorted order

sort - Sorts array elements in ascending or descending order

sortrows - Sorts rows in ascending order

squeeze - Removes singleton dimensions

transpose - Transpose

vectorize - Vectorizes expression


MATLAB Programming 45 - Array functions for dimentions


Length, Dimension and Number of elements:


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


x = [7.1, 3.4, 7.2, 28/4, 3.6, 17, 9.4, 8.9];
length(x) % length of x vector
y = rand(3, 4, 5, 2);
ndims(y) % no of dimensions in array y
s = ['Zara', 'Nuha', 'Shamim', 'Riz', 'Shadab'];
numel(s) % no of elements in s

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


ans =
8

ans =
4

ans =
23

Circular Shifting of the Array Elements:


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


a = [1 2 3; 4 5 6; 7 8 9] % the original array a
b = circshift(a,1) % circular shift first dimension values down by 1.
c = circshift(a,[1 -1]) % circular shift first dimension values % down by 1
% and second dimension values to the left % by 1.

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


a =
1 2 3
4 5 6
7 8 9

b =
7 8 9
1 2 3
4 5 6

c =
8 9 7
2 3 1
5 6 4


Monday, 1 August 2016

MATLAB Programming 44 - Colon Notation (Example)


Example


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


A = [1 2 3 4; 4 5 6 7; 7 8 9 10]
A(:,2) % second column of A
A(:,2:3) % second and third column of A
A(2:3,2:3) % second and third rows and second and third columns

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


A =
1 2 3 4
4 5 6 7
7 8 9 10

ans =
2
5
8

ans =
2 3
5 6
8 9

ans =
5 6
8 9

MATLAB Programming 44 - Colon Notation (2)


You can use the colon operator to create a vector of indices to select rows, columns or elements of arrays.

The following table describes its use for this purpose (let us have a matrix A): 


A(:,j) - is the jth column of A.

A(i,:) - is the ith row of A.

A(:,:) - is the equivalent two-dimensional array. For matrices this is the same as A.

A(j:k) - is A(j), A(j+1),...,A(k).

A(:,j:k) - is A(:,j), A(:,j+1),...,A(:,k).

A(:,:,k) - is the kth page of three-dimensional array A.

A(i,j,k,:) - is a vector in four-dimensional array A. The vector includes A(i,j,k,1), A(i,j,k,2), A(i,j,k,3), and so on.

A(:) - is all the elements of A, regarded as a single column. On the left side of an assignment statement, A(:) fills A, preserving its shape from before. In this case, the right side must contain the same number of elements as A.


MATLAB Programming 44 - Colon Notation (1)


Colon Notation


The colon(:) is one of the most useful operator in MATLAB. It is used to create vectors, subscript arrays, and specify for iterations.

If you want to create a row vector, containing integers from 1 to 10, you write:


1:10

MATLAB executes the statement and returns a row vector containing the integers from 1 to 10:


ans =
1 2 3 4 5 6 7 8 9 10

If you want to specify an increment value other than one, for example:


100: -5: 50


MATLAB executes the statement and returns the following result:


ans =
100 95 90 85 80 75 70 65 60 55 50

Let us take another example:


0:pi/8:pi

MATLAB executes the statement and returns the following result:


ans =
Columns 1 through 7
0 0.3927 0.7854 1.1781 1.5708 1.9635 2.3562
Columns 8 through 9
2.7489 3.1416



MATLAB Programming 43 - Sorting of arrays


Sorting Arrays


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


v = [ 23 45 12 9 5 0 19 17]      % horizonal vector
sort(v)      %sorting v
m = [2 6 4; 5 3 9; 2 0 1]      % two dimensional array
sort(m, 1)      % sorting m along the row
sort(m, 2)      % sorting m along the column

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


v =
23 45 12 9 5 0 19 17

ans =
0 5 9 12 17 19 23 45

m =
2 6 4
5 3 9
2 0 1

ans =
2 0 1
2 3 4
5 6 9

ans =
2 4 6
3 5 9
0 1 2


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