0% found this document useful (0 votes)
9 views

SOLUTION FOR MODEL PAPER2

The document provides solutions to a model question paper focused on MATLAB programming. It covers topics such as creating matrices, plotting functions, writing scripts and function files, and solving algebraic equations. Additionally, it explains various file types used in MATLAB and how to utilize the publisher feature for generating reports.
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)
9 views

SOLUTION FOR MODEL PAPER2

The document provides solutions to a model question paper focused on MATLAB programming. It covers topics such as creating matrices, plotting functions, writing scripts and function files, and solving algebraic equations. Additionally, it explains various file types used in MATLAB and how to utilize the publisher feature for generating reports.
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/ 14

SOLUTIONS TO MODEL QUESTION PAPER 2

Module -1:
1. a. With neat diagram explain MATLAB.

b .Write a MATLAB program to compute Area = 𝜋𝑟2 with r = 𝜋1/3 - 1. (𝜋Is pi in


MATLAB) (5M)

Ans: The arithmetic operation is …… (1)

Substitute in Equation (1).

Type >> area= pi*(pi^ (1/3)-1) ^2 in MATLAB command window and press enter.
The output after execution is,
area =0.6781 .Thus, the solution for the arithmetic operation is 0.6781.

2.a. Write a MATLAB program for the equation of a straight line is y = mx + c,


where m and c are constants. Compute the y-coordinates of a line with slope m =
0.5 and the intercept c = -2 at the following x-coordinates:
x = 0, 1.5, 3, 4, 5 , 7, 9, and 10 (5m)
Ans : An array is a set of expressions arranged in horizontal rows and vertical columns. The
array with size has m rows and n columns.
Step 1:
The equation of the straight line is y = mx + c Where, Slope constant m is 0.5. Intercept
constant c is – 0.2. y represents the y-coordinates. The x-coordinates are 0, 1.5, 3, 4, 5, 7, 9,
and 10.
Substitute 0.5 for m and - 0.2 for c in y= mx + c
Therefore, y = 0.5 x – 0.2
Step 2:
Type the following in MATLAB command window and press enter.
x = [0 1.5 3 4 5 7 9 10];
y = 0.5*x-2
The output after execution is,
y =-2.0000 -1.2500 -0.5000 0 0.5000 1.5000 2.5000 3.0000
Thus, the y-coordinates of the line for the x- coordinates are computed. The values are
-2.0000 -1.2500 -0.5000 0 0.5000 2.5000 3.0000

b. Explain various file types used in MATLAB (5M)


Ans: MATLAB can read and write several types of files.
There are mainly five different types of files for storing data or programs
M-files are standard ASCII text files, with a .m extension to the filename. There are two
types of these files: Script files and Function files. Most programs we write in MATLAB are
saved as M-files. All built-in function are in MATLAB are M-files, most of which reside on
our computer in precompiled format. Some built-in functions are provided with source code
in readable M-files so that they can be copied and modified.
Mat-files are binary data files, with a. mat extension to the filename. Mat-files are created by
MATLAB when you save data with the save command. The data is written in a special
format that only MATLAB can read. Mat-files can be loaded into MATLAB with the load
command.
Fig-files are binary figure files with a .fig extension that can be opened again in MATLAB as
figures. Such files are created by saving a figure in this format using the Save or Save As
options from the File menu or using the saveas command in the command window. A fig-file
contains all the information required to recreate the figure. Such files can be opened with the
open filename . fig command.
P-files are compiled M-files with a .p extension that can be executed in MATLAB
Directly. These files are created with the pcode command. If we develop an application that
other people can use but we do not want to give them the source code (M- file) , then we give
them the corresponding p-code or the p-file.
Mex-files are MATLAB-callable Fortran, C, and Java programs, with a . mex extension to
the filename. Use of these files requires some experience with MATLAB and a lot of
patience.
Module-2:
3 a. Write a MATLAB program Plot y = sin x, 0< x <2 𝜋, taking 100
linearly spaced
points in the given interval. Label the axes and put "Plot created by
your name" in
the title
Ans: The MATLAB command linspace creates an array of samples with linear spacing.
The plot function plots a data set by creating two vectors containing the x and y values to be plotted.
Title and axis labels are added to the plot with title, xlabel and ylabel functions.
The following is the MATLAB program to create a simple sine plot. Save the program as ‘sine_plot’.
x=linspace(0,2*pi,100);
plot(x, sin(x))
xlabel ('x');
ylabel('sin(x)');
title('Plot created by you name'); % add your name here
The resulting plot after executing the program is shown in Figure

b. Explain the steps involved in creating and executing a function file. (5M)
Ans: A function file is also an M-file, just like a script file, except it has a function definition
line on the top that defines the input and output explicitly.
How to create and execute a function file:
Method : Example: Write a function file to draw a circle of a specified radius, with the
radius as the input to the function.
1. Open the script file circle. m:
• On PCs: Select File---->Open ... from the File menu. Navigate and select the file circle.m from the
Open dialog box. Double-click to open the file. The contents of the file should appear in an edit
window.
2. Edit the file circle .m
function [x , y] = circlefn (r) ;
% CIRCLEFN - Function to draw a circle of radius r.
% File written by Rudra Pratap on 9/ 17/94. Last modified 7/ 1 /98
% Call syntax : [x , y] = circlefn (r) ; or just : circlefn (r) ;
% Input : r = specified radius
% Output : [x , y] = the x- and y-coordinates of data points
theta=linspace ( 0 , 2*pi , 100) ; % create vector theta
x = r*cos (theta); % generate x-coordinates
y = r*sin (theta) ; % generate y-coordinates
plot (x , y) ; % plot the circle
axis ( ' equal') ; % set equal scale on axes
title ( [ ' Circle of radius r = ' , num2str (r) ] ) % put a title with the value of r
Alternatively, you could select File---->New---->Function M-File and type all the
lines in the new file.
3. Now write and save the file under the name circlefn.m as follows:
• On PCs: Select Save As ... from the File menu. A dialog box should appear. Type circlefn .m as the
name of the document. Make sure the file is saved in the folder you want (the current working
folder/ directory of MATLAB). Click Save to save the file.
Executing a function file:
>> R = 5; % Specify the input and execute the function with an explicit output list.
>> [x , y] = circlefn (R) ;
>> [ cx, cy ] = circlefn ( 2.5 ) ; % You can also specify the value of the input directly.
>> circlefn ( 1) ; % If you don't need the output, you don't have to specify it.
>> circlefn ( R^2 / (R+5* sin (R) )); %Of course, the input can also be a valid MATLAB
expression.
Note: 1. A function file (see previous page) must begin with a function definition line.
2. The argument of the title command in this function file consists of two character strings. The first
one is a simple character string, ' Circle of radius r ='. The second one, num2str (r), is a function that
converts the numeric value of r to a string (and hence the nameof the function) . The square brackets
create an array of the two strings by concatenating them.

4. a. Write a MATLAB code to create a 4*4 matrix.


Ans: Creating Matrices:
The most direct way to create a matrix is to type the matrix row by row, separating
the elements in a given row with spaces or commas and separating the rows with
semicolons.
Code to create a 4x4 matrix
>> A = [1 3 5 7; 2 4 6 8; 7 8 10 12] % Matrices are entered row-wise. Rows are separated by
semicolons and columns are separated by spaces or commas.
A = 4×4
Ans =
1 3 5 7
2 4 6 8
7 8 10 12

b. Explain the steps involved in creating and executing a script file.


Ans : A script file is a user-created file with a sequence of MATLAB commands in it . The
file must be saved with a . m extension to its name, thereby, making it an M-jile. A script
file is executed by typing its name (without the .m extension) at the command prompt .
How to create and execute a Script file:
Method: Example: Write a script file to draw the unit circle.
1. Create a new file:
• On PCs and Macs: Select FileNewBlank M-File from the File menu. A new edit window
should appear.
2. Type the following lines into this file. Lines starting with a % sign are interpreted as comment lines
by MATLAB and are ignored.
% CIRCLE - A script file to draw a unit circle
% File written by Rudra Pratap . Last modified 5/28/98
% -------------------------
theta=linspace ( 0 , 2*pi , 100) ; % create vector theta
x= cos (theta) ; % generate x-coordinates
y=sin (theta) ; % generate y-coordinates
plot (x , y) ; % plot the circle
axis ( ' equal ') ; % set equal scale on axes
title ( ' Circle of unit radius ') % put a title
3. Write and save the file under the name circle. m:
• On PCs: Select Save As... From the File menu. A dialog box should appear. Type circle .m as the
name of the document. Make sure the file is being saved in the folder you want it to be in (the current
working folder/directory of MATLAB). Click Save to save the file.
4. Executing a script file.
>> help circle % Seek help on the script file to see if MATLAB can access it.
CIRCLE - A script file to draw a unit circle %MATLAB lists the comment lines of the file as
on-line help.
>> circle % Execute the file. You should see the circle plot in the figure window.
5. If you have the script file open in the MATLAB editor window, you can also
execute the file by pressing the Run file icon or the F5 function key.
Module-3:
5. a. Write a MATLAB code to compute the following expression (5M)
f(x) =𝑥4 − 8𝑥3 + 17𝑥2 − 4𝑥 – 20.
Ans: f(x) = x4 - 8x3 +17x2 -4x -20
The MATLAB command to represent exponent is ‘^’ and for division is ‘*’
>> f(x) = x^4 -8 *x^3 +17*x^2 -20
f=
x^4 -8 *x^3 +17*x^2 -20 % Create a function f(x)
>> f(0) % Evaluate the function at x == 0, i.e. ,find f(0).
ans =
-20
>> f(1) % Evaluate the function at x == 1.
Ans =
-10

b. Explain how to use publisher from the editor window with example. (5M)
Ans: MATLAB includes an automatic report generator called publisher.
This publisher is accessible, like many other utilities, both from the menu and
the command line. The publisher publishes a script in several formats, including
HTML, XML, MS Word, PowerPoint, etc.
Using the publisher from the editor window:
Open the file circle.m .You can open the file by following File ---> Open from the menu or from
the command window with either circle .m or open circle .m . Once the file is open in the editor,
select Publish from the File menu of the editor window, or click on the publish icon icon (next to
the printer icon in the menubar) . The script open in the editor will be published to an HTML file
and MATLAB will automatically open the HTML file for your perusal.

6. a. Write a MATLAB code to solve the following set of simultaneous linear algebraic
equations. x+ 3y –z=2 (5M)
x-y+z=3

3x - 5y =4.

Ans: First initialize the symbolic variables x , y, z . And then write the appropriate code to represent
expressions.

>> syms x y z

>> exp1 = ‘ x + 3 * y - z – 2’ % Solve three simultaneous algebraic equations for x and y and
z

>> exp 2 = ‘ x – y +z -3’

>> exp 3 = ‘ 3 * x – 5 * y - 4’

>> [ x , y , z ] = solve (exp1 , exp2 , exp 3 )

b. Explain three different kinds of files for reading data into MATLAB's workspace

Module-4:

7. a. How to name variables, what is the precision of computation and


how to recall previously typed commands? (5M)

Variable Names

Valid Names:

A valid variable name starts with a letter, followed by letters, digits, or


underscores. MATLAB® is case sensitive, so A and a are not the same variable.
The maximum length of a variable name is the value that the namelengthmax
command returns.

Avoid creating variables with the same name as a function (such as i, j, mode,
char, size, and path). In general, variable names take precedence over function
names. If you create a variable that uses the name of a function, you sometimes
get unexpected results.

The interactive mode of computation, however, makes MATLAB a powerful


scientific calculator that puts hundreds of built-in mathematical functions for
numerical calculations

How to name variables: Names of variables must begin with a letter. After the first letter, any number
of digits or underscores may be used, but MATLAB remembers only the. first 31 characters.
What is the precision of computation: All computations are carried out internally in double precision
unless specified otherwise. The appearance of numbers on the screen, however, depends on the format
in use. The output appearance of floating-point numbers (number of digits after the decimal, etc.) is
controlled with the format command. The default is format short , which displays four
digits after the decimal.
How to recall previously typed commands: Use the up-arrow key to recall previously typed
commands. MATLAB uses smart recall, so you can also type one or two letters of your command and
use the up-arrow key for recalling the command starting with those letters. Also, all your commands
are recorded in the command history subwindow. You can double-click on any command in the
command history subwindow to execute it inthe command window.

b. With example explain input in matrices and vectors? (5M)


Ans: Input
A matrix is entered row-wise, with consecutive elements of a row separated by a space or a comma,
and the rows separated by semicolons or carriage returns. The entire matrix must be enclosed within
square brackets. Elements of the matrix may be real numbers, complex numbers, or valid MATLAB
expressions.
Examples:
Matrix
A = [1 2 5
3 9 0] MATLAB input command
A = [1 2 5; 3 9 0]
B = [2x lnx +siny
5i 3+2i ] B = [2*x log (x) +sin (y) ; 5i 3+2i]
Note : For the matrix B command to work, variables x and y must be predefined, e.g. , x=l; y=2;, etc.
Special cases: Vectors and scalars
• A vector is a special case of a matrix, with just one row or one column. It is
entered the same way as a matrix.
Examples: u = [1 3 9] produces a row vector, and
v = [1 ; 3; 9] produces a column vector.

• A scalar does not need brackets.


Example: g = 9. 81 ;
• Square brackets with no elements between them create a null matrix.
Example: X = [ ].
Continuation :
If it is not possible to type the entire input on the same line, then use three consecutive periods ( . . . )
to signal continuation and continue the input on the next line.
The three periods are called an ellipsis. For example,
A = [1/3 5. 55*sin (x) 9.35 0.097 ; . . .
3/ (x+2*log (x) ) 3 0 6.555 ; .. .
( 5*x-23) /55 x-3 x*sin(x) sqrt (3) ] ;
produces the intended 3 x 4 matrix A.
A matrix can also be entered across multiple lines using carriage returns at the end of each row. In this
case, the semicolons and ellipses at the end of each row may be omitted. Thus, the following three
commands are equivalent:
A = [1 3 9; 5 10 15 ; 0 0 -5] ;
A = [1 3 9
5 10 15
0 0 -5];
A [1 3 9; 5 10 ...
15; 0 0 -5] ;

8. a. Explain the steps in creating vector


Ans: Creating vector: To create a vector of numbers over a given range with a specified
Increment. The general command to do this in MATLAB is
v = Initial Value: Increment: Final Value
The three values in the preceding assignment can also be valid MATLAB expressions. If no
increment is specified, MATLAB uses the default increment of 1.
Examples:
a = 0:10:1 00 produces a= [0 10 20 100],
b = 0: pi/50: 2*pi produces b = [0 ∏ /50 2∏ /50 ………2∏], i.e., a linearly
Spaced vector from 0 to 2∏ spaced at ∏/50.
u = 2: 10 produces a= [ 2 3 4 10 ].
linspace ( a ,b, n) generates a linearly spaced vector of length n from a to b.
Example: u=linspace (0, 20, 5) generates u= [0 5 10 15 20].
Thus, u=linspace (a, b, n) is the same as u=a: (b-a) / (n-1): b.
logspace (a, b,n) generates a logarithmically spaced vector of length n from
10a to 10b.
Example: v = logspace (0, 3, 4) generates v = [1 10 100 1000].
Thus, logspace (a, b, n) is the same as 10. ^ (linspace (a, b, n)).
Special vectors, such as vectors of zeros or ones of a specific length, can be created with the utility
matrix functions zeros, ones, etc.
Examples:
u = zeros ( 1 , 1000) initializes a 1000-element-long row vector, and
v = ones ( 10, l) creates a 10-element-long column vector of ones.

b. Explain built-in functions of MATLAB.


Ans: MATLAB provides hundreds of built-in functions for numerical linear algebra, data
analysis, Fourier transforms, data interpolation and curve fitting, root-finding, numerical
solution of ordinary differential equations, numerical quadrature, sparse matrix calculations,
and general-purpose graphics. There is on-line help for all built-in functions.
help: the most direct on-line help: If you know the exact name of a function, you can get
help on it by typing help functionname on the command line. For example, typing help help
provides help on the function help itself.
lookfor : the keyword search function: If you are looking for a function, use lookfor
keyword to get a list of functions with the string keyword in their description. For example,
typing lookfor ' identity matrix ' lists functions (there are two of them) that create identity
matrices.
helpwin : click and navigate help:
To activate the help window, type helpwin at the command prompt or select Help Window
from the Help menu on the command window menu bar.
helpdesk: the web browser based help: bar. MATLAB provides extensive on-line
documentation in both HTML and PDF formats, If you like to read on-line documentation
and get detailed help by clicking on hyperlinked text, use the web browser-based help
facility, helpdesk. To activate the help window, click on the help icon. on the menu bar.
Alternatively, type helpdesk at the command prompt or select Product Help from the Help
menu on the command window menu bar.
Example:
>> help determinant % To use help you should know the exact name of the function
determinant . m not. found .
>> lookfor determinant %To find the function, use the keyword search command lookfor
det - Determinant .

Module-5 :
9. a Explain script files with example.
Ans: Script Files
A script file is an M-file with a set of valid MATLAB commands in it. A script file is
executed by typing the name of the file (without the .m extension) on the command
line. It is equivalent to typing all the commands stored in the script file, one by
one , at the MATLAB prompt. Naturally, script files work on global variables, that
is, variables currently present in the workspace. Results obtained from executing
script files are left in the workspace. Script files are useful when you have
to repeat a set of commands several times.
Example of a script file:
Let us write a script file to solve the following system of linear equations:
5 2r r x1 2
3 6 2r-1 x2 = 3
2 r-1 3r x3 5

or Ax = b. Clearly, A depends on the parameter r. We want to find the solution


of the equation for various values of the parameter r. rite a set of MATLAB commands
that do the job and store these commands in a file called solvex. m.
%----------- This is the script file ' solvex . m' -----------
% It solves equation for x and also calculates det (A) .
A = [5 2*r r ;3 6 2*r- 1; 2 r-1 3*r] ; % create matrix A
b = [2 ; 3; 5] ; % create vector b
det_A = det (A) % find the determinant
X = A\b % find x
The results will be stored in variables det_A and x, and these will be left in the workspace.
>> clear all % clear workspace
>> r = 1; % specify a value for r
>> solvex % execute the script file solvex .m
>> det _A This is the output. The values of the variables det_A and x
appear on the screen because there is no semicolon at the end of the corresponding lines in
the script file.
= 64
x=
-0.0312
0.2344
1.6875
>> who % Check the variables in the workspace.

b. Explain function files with example. (5M)


Ans : A function file is also an M-file, like a script file, except that the variables in a function
file are all local. Function files are like programs or subroutines in Fortran, procedures in
Pascal, and functions in C.
A function file begins with a function definition line, which has a well-defined
list of inputs and outputs. Without this line, the file becomes a script file. The
syntax of the function definition line is as follows:
function [output variables] = function_name( input variables) ;
where the function_name must be the same as the file name (without the .m exten-
sion) in which the function is written. For example, if the name of the function is
projectile it must be written and saved in a file with the name projectile.m. The
function definition line may look slightly different, depending on whether there is
no output, a single output, or multiple output.
Let us write a function file to solve the same system of linear equations
5 2r r x1 2
3 6 2r-1 x2 = 3
2 r-1 3r x3 5

This time, we will make T an input to the function and det_A and x will be the output.
Let us call this function solvexf . As a rule, it must be saved in a file called solvexf. m.
function [det _A , x] = solvexf (r) ;
% SOLVEXF solves a 3X3 matrix equation with parameter r
% This is the funct ion f ile ' solvexf .m'
% To call this funct ion , type :
% [det_A , x] = solvexf (r) ;
% r is the input and det_A and x are output .
% ______________________________ ______________________ _
A [5 2*r r; 3 6 2*r- 1 ; 2 r-1 3*r] ; % create matrix A
b= [2 ; 3 ; 5] ; % create vector b
det_A = det (A); % find the determinant
X = A\b ; % find x
Now r, x, and det_A are all local variables. Therefore, any other variable names
may be used in their places in the function call statement. Let us execute this
function in MATLAB.
>> clear all
>> [det A , y] = solvefx(1) % take r =1 and solvexf.m
>> det A
det A
= 64
>> y % display the value of y
Y=
-0.0312
0.2344
1.6875 % Values of detA and y will be automatically displayed if the semi-
colon at the end of the function command is omitted.
>> who % Note that only detA and y are in the workspace; no A, b, or x.
Your variables are
det A y
After execution of a function, the only variables left in the workspace by the
function will be the variables in the output list. This gives us more control over
input and output than we can get with script files.

10. a. Explain 2 ways for executing a function(5M)


Ans: There are two ways a function can be executed, whether it is built-in or user-written:
1. With explicit output: This is the full syntax of calling a function. Both the output and input
list are specified in the call. For example, if the function definition line of a function reads
function [rho ,H,F] = motion (x ,y, t ) ;
then all the following commands represent legal call (execution) statements:
• [r , angmom , force] =motion(xt , yt, time ) ; The input variables xt, yt,
and time must be defined before executing this command.
• [r , h, f] =mot ion (rx , ry , [0 : 100] ) ; The input variables rx and ry
must be defined beforehand; the third input variable t is specified in
the call statement.
• [r ,h, f] =motion (2 .3.5.0.001) ; All input values are specified in the
call statement .

• [radius , h] =mot ion (rx , ry) ; Call with partial list of input and out-put . The third input
variable must be assigned 11 default value inside the function if it is required in calculations.
The output corresponds to the first two elements of the output list of motion.
2. Without any output: The output list can be omitted entirely if the computed quantities are
not of any interest. This might be the case when the function displays the desired result
graphically. To execute the function this way, just type the name of the function with the
input list. For example,motion (xt , yt , time ) ; will execute the function mot ion without
generating any explicit output, provided that xt, yt, and time are defined. If the semi-colon at
the end of the call statement is omitted, the first output variable in the output list of the
function is displayed in the default variable ans.

b. Explain the Recursion in MATLAB.(5M)


Ans: The MATLAB programming language supports recursion, i.e. , a function can call
itself during its execution. Thus, recursive algorithms can be directly implemented
in MATLAB.
To illustrate this , let us look at a simple example of computing the nth term in the Fibonacci
sequence ( actually, first discovered by Pingala (300-200 BCE) , an ancient Indian
mathematician): 0, 1, 1, 2, 3, 5, 1:, .•• . If we label the terms as F0 , F1 , F2 , etc., then the
recursion relationship for generating this sequence is: Fk = Fk-l + Fk-2 for k> 2. The seeds
arc F0 = 0 and F1 = F2 = 1. The nth term in this sequence can be computed by
the following recursive function:
function Fn = fibonacci (n)
% FIBBONACI : computes nth t erm in the Fibonacci sequence
% written by Abhay , May 15 , 09 , modif ied by RP , June 1, 09
if n==O , Fn = 0; % Fn=O for n=O
elseif n== 1 | n==2 , Fn = 1; % Fn= 1 , f or n=1 OR n=2
else Fn = fibonacci (n-1) + fibonacci (n-2) ; % recursion relation
end

You might also like