0% found this document useful (0 votes)
21 views20 pages

BEC358B Model Papers-solutions (1)

This document is a model question paper for the MATLAB Programming course for the third semester B.E. degree examination, effective from the academic year 2023-24. It includes various questions divided into modules covering topics such as MATLAB features, array operations, plotting functions, anonymous functions, data import/export, and function files. The exam consists of five questions, with students required to answer at least one question from each module.

Uploaded by

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

BEC358B Model Papers-solutions (1)

This document is a model question paper for the MATLAB Programming course for the third semester B.E. degree examination, effective from the academic year 2023-24. It includes various questions divided into modules covering topics such as MATLAB features, array operations, plotting functions, anonymous functions, data import/export, and function files. The exam consists of five questions, with students required to answer at least one question from each module.

Uploaded by

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

BEC358B

Model Question Paper-I with effect from 2023-24 (CBCS Scheme)


USN

Third Semester B.E. Degree Examination


MATLAB Programming
TIME: 02 Hours Max. Marks: 50

Note: 01. Answer any FIVE full questions, choosing at least ONE question from each MODULE.

Q.No Question M L CO
MODULE-1
a. Explain the features and capabilities of MATLAB 5 L2 CO1

Page 01 of 02
BEC358B

b. Write a MATLAB commands for following expressions 5 L2 CO1

Answer for (i), (ii), (iii)

Answer for (iv), (v)

OR
a. Demonstrate array operations in MATLAB with suitable examples 5 L2 CO1
Page 01 of 02
BEC358B
Answer
Array operations
·* term-by-term multiplication,
./ term-by-term division,
. ^ term-by-term exponentiation
2 Example:

b. Write a MATLAB commands for following expressions 5 L2 CO1

Answer for
{i), (ii)

Answer for
{iii), (v), (iv)

Page 01 of 02
BEC358B
MODULE-2
a. Write a MATLAB program to plot a circle of unit radius with comments 5 L2 CO2

b. With respect to the MATLAB script files explain the commands 5 L2 CO2
i. to see the variables present in your workspace: who
ii. to get more information about the variables and the
workspace: whos
iii. to see the contents of an M-file without opening the file
with an editor: Command: type filename.m
iv. to look for M-files with keywords in their description:
Command: help keyword
v. to ask the user to input on the screen: Command:
input(prompt)
Example: userInput = input('Enter a number: '); This will prompt the user to
enter a number, and the input will be stored in the variable userInput .

OR
a. Write a MATLAB commands to Plot y = sin x, 0 ≤ x ≤ 2π, taking 100 linearly 5 L2 CO2
spaced points in the given interval. Label the axes and put ‘Plot created by
4 your name’ in the title
Answer

b. Write a MATLAB function to compute the factorial n! for any integer n. The 5 L2 CO2

Page 01 of 02
BEC358B
input should be the number n and the output should be n!.

Answer

MODULE-3
a. What are anonymous functions? Explain with example 5 L2 CO3
Answer
An anonymous function is a function of one or more variables that you create on the
command line for subsequent evaluation. Such a function is especially useful if you
5 need to evaluate the function several times (with different input) during a single
MATLAB session and you do not care to code it in a function file and save for later
use.
For example, let us say that we have f(x) = x3 - 3x2 + xlog(x-1) + 100, and we need to
evaluate this function at different values of x, plot it over certain range of x, or find the
zeros of f (x) . For such computations, we can define f (x) as an anonymous function
and evaluate it at any value(s) of x or use this function as an input to other functions
that need such input.

b. Create three anonymous functions corresponding to the following expression 5 L2 CO3

Answer
f = @(x) x^4-8*x^3+17*x^2-4*x-20
g= @(x) x^2-4*x+4
h = @(x) x^2-4*x-5

OR
a. Explain MATLAB commands to import and export data with suitable example 5 L2 CO3
Answer (Refer page no. 51, 52, 53 in text book)

MATLAB provides several functions for importing and exporting data from
various file formats. Two commonly used functions are load and save for
importing and exporting data, respectively.
Page 02 of 02
BEC358B
Saving into and loading from the binary Mat-files

6 The save command can be used to save either the entire workspace or a few selected
variables in a file called Mat-file. Mat-files are written in binary format with full 16-bit
precision. It is also possible to write data in Mat-files in 8-digit or 16-digit ASCII
format with optional arguments to the save command (see the on-line help) . Mat-files
must always have a . mat extension. The data saved in these files can be loaded into the
MATLAB workspace by the load command. Examples of proper usage of these
commands are as follows:

ASCII datafiles can also be loaded into the MATLAB workspace with the load
command provided the datafile contains only a rectangular matrix of numbers.

We can also usc cut-and-paste between the MATLAB command window and other
applications (such as Microsoft Excel) to import and export data.

Importing data files

We can import data from a Microsoft Excel spreadsheet into MATLAB. MATLAB
also provides a special function xlsread for reading Excel's spreadsheets as .xls files.

MATLAB incorporates a good interface for importing different types of datafiles, hoth
through GUI and the command-line. The easiest way to import data from a file is to
invoke the import wizard by either (i) selecting Import Data from the File menu of the
MATLAB window or (ii) typing uiimport on the command line and then following the
instructions on the screen.
Import wizard can load data from several file formats used for text data, spreadsheet
data (.xls, .wkl) , movie data (.avi) , image data (.tiff, .jpeg, etc.), and audio data (.wav,
.au).
An entire MATLAB session, or part of one, can be recorded in a user-editable file by
means of the diary command.

b. Define the following function symbolically 5 L2 CO3


2 2
f(x) = (x - 4x) (x - 4x + 1) - 20.
i. Write the command for Expand f(x)
ii. Write command to Factorize f using the symbolic function
iii. Write command to Solve the following nonlinear algebraic equations
simultaneously.

Answer
>>x=sym(‘x’)
>>f=(x^2- 4*x)*(x^2– 4*x + 1) – 20
(i)
>>expand(f)

Page 02 of 02
BEC358B
(ii)
>>factor(f)
(iii)
>>syms x y z
>>exp1=’x+3*y-z==2’
>>exp2=’x-y+z==3’
>>exp3=’3*x-5*y==4’
>>[x,y,z]=solve(exp1, exp2, exp3)

MODULE-4
a. Write a MATLAB command to 5 L2 CO4
i. Create a nxn matrix
ii. creates an n by n identity matrix.
iii. creates an n by n zero matrix.
iv. creates an n by n unit matrix.
v. to pulls out the diagonal elements
Answer: (i)
7 n = 3; % Define the size of the matrix (n x n)
A = rand(n); % Create a random nxn matrix
disp('Random nxn matrix:');
disp(A);
(ii)
n = 4; % Define the size of the identity matrix (n x n)
I = eye(n); % Create an nxn identity matrix
disp('Identity matrix:');
disp(I);
(iii)
n = 3; % Define the size of the zero matrix (n x n)
Z = zeros(n); % Create an nxn zero matrix
disp('Zero matrix:');
disp(Z);
(iv) n = 3; % Define the size of the unit matrix (n x n)
U = ones(n); % Create an nxn unit matrix
disp('Unit matrix:');
disp(U);
(v) % Let's say we have a matrix A
A = [1 2 3; 4 5 6; 7 8 9]; % Example matrix
diagonal_elements = diag(A); % Extract diagonal elements
disp('Diagonal elements:');
disp(diagonal_elements);
b. Write the output of the following MATLAB commands 5 L2 CO4
i. a = 0:10:100
ii. b = 0:pi/50:2*pi
iii. >> d = [2 4 6 8];
>> d1 = [-3 -3 -3];
>> d2 = [-1 -1];
>> D = diag(d) + diag(d1,1) + diag(d2,-2)
iv. B = [ones(3) zeros(3,2); zeros(2,3) 4*eye(2)]
Answer
(i) a = 0 10 20 30 40 50 60 70 80 90 100
Page 02 of 02
BEC358B
(ii)
b=

Columns 1 through 8

0 0.0628 0.1257 0.1885 0.2513 0.3142 0.3770 0.4398

Columns 9 through 16

0.5027 0.5655 0.6283 0.6911 0.7539 0.8168 0.8796 0.9424

Columns 17 through 24

1.0053 1.0681 1.1310 1.1938 1.2566 1.3195 1.3823 1.4451

Columns 25 through 32

1.5079 1.5708 1.6336 1.6964 1.7593 1.8221 1.8849 1.9478

Columns 33 through 40

2.0106 2.0734 2.1363 2.1991 2.2619 2.3248 2.3876 2.4504

Columns 41 through 50

2.5133 2.5761 2.6390 2.7018 2.7646 2.8275 2.8903 2.9531 3.0159


3.0788

(iii)
D=

2 -1 0 0
-3 4 -1 0
0 -3 6 -1
0 0 -3 8

(iv)
B=

1 1 1 0 0
1 1 1 0 0
1 1 1 0 0
0 0 0 4 0
0 0 0 0 4
OR
a. Explain the following MATLAB commands with suitable examples. 5 L2 CO4
i. Plot
ii. ezplot
8 iii. fplot
iv. ezpolar
v. ezplot3
Answer
(i) plot : This command is used to create 2D plots in MATLAB. It's a versatile
function that can be used to visualize data, mathematical functions, and
more. It takes in at least two input arguments, which are the x-coordinates
Page 02 of 02
BEC358B
and y-coordinates of the points to be plotted.
Ex :
x = linspace(0, 2*pi, 100); % Generate x values from 0 to 2*pi
y = sin(x); % Compute corresponding y values
plot(x, y); % Plot y = sin(x)
xlabel('x'); % Label x-axis
ylabel('sin(x)'); % Label y-axis
title('Plot of sin(x)'); % Add title
grid on; % Turn on grid
(ii) ezplot : This command is used to plot symbolic expressions or functions
defined by anonymous functions.
Ex :
ezplot('sin(x)', [0, 2*pi]); % Plot sin(x) from 0 to 2*pi
xlabel('x'); % Label x-axis
ylabel('sin(x)'); % Label y-axis
title('Plot of sin(x)'); % Add title
grid on; % Turn on grid
(iii) fplot : Similar to ezplot , fplot is used to plot functions. However, it's more
versatile and allows plotting of functions defined by MATLAB functions,
anonymous functions, or function handles.
Ex :
f = @(x) x.^2 - 2*x + 1; % Define a function using an anonymous function
fplot(f, [-1, 3]); % Plot the function from -1 to 3
xlabel('x'); % Label x-axis
ylabel('f(x)'); % Label y-axis
title('Plot of f(x) = x^2 - 2x + 1'); % Add title
grid on; % Turn on grid
(iv) ezpolar : This command is used to plot polar coordinates. It's similar to
ezplot but for polar coordinates. You provide a polar expression or function,
and ezpolar generates the corresponding plot.
Ex :
ezpolar('cos(3*theta)'); % Plot a polar function cos(3*theta)
title('Plot of cos(3*theta) in Polar Coordinates'); % Add title
(v) ezplot3 : This command is used to plot 3D curves defined by symbolic
expressions or functions. It's an extension of ezplot to three dimensions.
Ex :
ezplot3('sin(t)', 'cos(t)', 't', [0, 2*pi]); % Plot the 3D curve defined by x =
sin(t), y = cos(t), z = t from 0 to 2*pi
xlabel('x'); % Label x-axis
ylabel('y'); % Label y-axis
zlabel('t'); % Label z-axis
title('Plot of 3D Curve: x = sin(t), y = cos(t), z = t'); % Add title
grid on; % Turn on grid

b. Explain relational operators in MATLAB with suitable examples. 5 L2 CO4


Answer

Page 02 of 02
BEC358B

MODULE-5

Page 02 of 02
BEC358B
a. Describe the anatomy of function file in MATLAB and explain 5 L2 CO5
Answer

Answer

Example:

Example:

b. Write a script file named sineseries.m that computes the value of sin(x) at a 5 L2 CO5
given x using n terms of the series expansion of sine function

Answer:
Here's the MATLAB script file named sineseries.m that computes the value of sin(x) at
a given x using n terms of the series expansion of the sine function sin(x) = x - (x^3)/3!
+ (x^5)/5! - ...:
function result = sineseries(x, n)
% Initialize result to store the value of sin(x)
result = 0;

% Compute the value of sin(x) using n terms of the series expansion


for k = 0:n-1
% Compute the k-th term of the series expansion
term = ((-1)^k) * (x^(2*k+1) / factorial(2*k+1));

% Add the term to the result


result = result + term;
end
end
We can call this function from the MATLAB command window or from another script by
passing the desired value of x and n . For example:
x = pi/4; % Value of x
Page 03 of 02
BEC358B
n = 10; % Number of terms in the series expansion
result = sineseries(x, n); % Compute sin(x) using n terms
disp(['sin(', num2str(x), ') using ', num2str(n), ' terms: ', num2str(result)]);

OR
a. Explain MATLAB control flow statements like for-loops, while loops and, of 5 L2 CO5
10 course, if-elseif-else branching with suitable examples

Answer:

Answer:

k=1;
end
b. Write a short note on MATLAB Profiler. 5 L2 CO5

Answer:

Page 03 of 02
BEC358B

Answer:

Page 03 of 02
BEC358B
Model Question Paper-II with effect from 2023-24 (CBCS Scheme)
USN

Third Semester B.E. Degree Examination


MATLAB PROGRAMMING
TIME: 02 Hours Max. Marks: 50

Note: Answer any FIVE full questions, choosing at least ONE question from each MODULE.

*Bloom’s
Module -1 Taxonomy Marks
Level
Q.01 a With neat diagram explain MATLAB L2 5
(same as in previous paper Q1a)
b Write a MATLAB program to compute Area = 𝜋𝑟2 with r = 𝜋1/3 - 1. (𝜋Is pi in L3 5
MATLAB) (same as in previous paper Q1b iii)
OR
Q.02 a Write a MATLAB program for the equation of a straight line is y = mx + c, L3 5
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
Answer:

b Explain various file types used in MATLAB L2 5


Ans:
File types
• M-files are standard ASCII text files, with a .m extension to the filename. Most
programs you write in MATLAB are saved as M-files.

• Mat-files are binary datafiles, with a . mat extension to the filename. Mat-files
are created by MATLAB when you save data with the save 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 save as command in
the command window. A figfile 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 (without being parsed and compiled) . These files are created
with the pcode command. If you develop an application that other people can use
but you do not want to give them the source code (M- file) , then you give them
the corresponding p-code or the p-file.
Module-2
Q. 03 a Write a MATLAB program Plot y = sin x, 0< x <2 𝜋, taking 100 linearly spaced L3 5
points in the given interval. Label the axes and put "Plot created by yourname" in
the title.

b Explain the steps involved in creating and executing a function file. L2 5


Page 01 of 02
BEC358B
 Open the MATLAB Editor by either clicking on the "New Script"
button in the MATLAB toolbar or by typing edit in the
Command Window followed by the name of your function file.
 In the Editor, write your MATLAB function. The function should
start with the function keyword followed by the output
arguments and the function name. Then, specify the input
arguments within parentheses. After that, write the body of the
function.
 Save the file with a meaningful name and the .m extension. The
file name should match the function name exactly.

To execute the function, you can call it from the MATLAB Command
Window or from another script or function. Simply type the function name
followed by the necessary input arguments in parentheses.
Example:
% Step 1: Create the function file named myFunction.m
% Step 2: Define Inputs and Outputs
function output = myFunction(input)
% Step 3: Write the Function Body
output = input^2; % Compute the square of the input
end

% Step 5: Execute the Function


result = myFunction(3); % Call the function with input value 3

% Step 6: View Output


disp(result); % Display the result

OR
Q.04 a Write a MATLAB code to create a 4*4 matrix L3 5

This code creates a 4x4 matrix named matrix with elements ranging from 1
to 16. You can modify the elements of the matrix as per your requirements.
The disp function is used to display the matrix in the MATLAB Command
Window.
% Define the elements of the matrix
matrix = [1, 2, 3, 4;
5, 6, 7, 8;
9, 10, 11, 12;
13, 14, 15, 16];

% Display the matrix


disp('4x4 Matrix:');
disp(matrix);
b Explain the steps involved in creating and executing a script file. L2 5
Ascript 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 .
Example:
% Step 1: Open MATLAB Editor and create a new script file

% Step 2: Write Your MATLAB Code


a = 5; % Assign a value to variable 'a'
b = 3; % Assign a value to variable 'b'
c = a + b; % Calculate the sum of 'a' and 'b'

% Step 3: Save the Script File


% Save the script file with a meaningful name, such as 'myscript.m'

% Step 4: Execute the Script


% Run the script by clicking the 'Run' button in the MATLAB Editor toolbar or by
Page 01 of 02
BEC358B
typing the script name in the Command Window and pressing 'Enter'

% Step 5: View Output


disp(['The sum of a and b is: ', num2str(c)]); % Display the sum of 'a' and 'b' in the
Command Window
Module-3
Q. 05 a Write a MATLAB code to compute the following expression L3 5
f(x)=𝑥4 − 8𝑥3 + 17𝑥2 − 4𝑥 – 20

An anonymous function is a function of one or more variables that you


create on the command line for subsequent evaluation
For example, let us say that we have f(x) = x3 - 3x2 + xlog(x-1) + 100, and
we need to evaluate this function at different values of x, plot it over
certain range of x, or find the zeros of f (x) . For such computations, we
can define f (x) as an anonymous function and evaluate it at any value(s)
of x or use this function as an input to other functions that need such input.

Now, the MATLAB code to compute the following expression


f(x)=𝑥4 − 8𝑥3 + 17𝑥2 − 4𝑥 – 20 is

>>f = @(x) x^4-8*x^3+17*x^2-4*x-20


To Evaluate the function at x == 0,
>>f(0)
To Evaluate the function at x == 1,
>>f(1)
We can use f in an array also
>> vaues [ f (0) f ( 1) f ( 2) f ( 10) ]

b Explain how to use publisher from the editor window with example L2 5
The MATLAB Editor's "Publish" feature, also known as "MATLAB Publisher,"
allows you to create formatted documents that combine MATLAB code,
results, and narrative text. This is useful for creating reports, tutorials, and
documentation.
Here's an example of how to use the Publisher from the Editor window:
%% Section 1: Introduction
% This script demonstrates how to use the MATLAB Publisher from the Editor
window.

%% Section 2: MATLAB Code


% Define variables
a = 5;
b = 3;

% Calculate sum
c = a + b;

% Display result
disp(['The sum of a and b is: ', num2str(c)]);

%% Section 3: Conclusion
% In this script, we showed how to use the MATLAB Publisher to create
formatted documents.
After writing this script, you can publish it by clicking the "Publish" button
in the MATLAB Editor toolbar. MATLAB will generate a formatted
document containing the code, comments, and output.
OR
Q. 06 a Write a MATLAB code to Solve the following set of simultaneous linear L3 5
algebraic equations.
x+ 3y –z=2
x-y+z=3
3x - 5y =4.
(see previous paper Q6iii)
b Explain three different kinds of files for reading data into MATLAB's workspace L2 5
Page 01 of 02
BEC358B
Three different kinds of files for reading data into MATLAB's workspace:
• Mat-file: This is MATLAB's native binary format file for saving data. Two
commands , save and load make it particularly easy to save data into and load data
from these files
Example: Saving data to a MAT file named data.mat :
x = [1, 2, 3, 4, 5];
save('data.mat', 'x');
Reading data from the MAT file:
load('data.mat');

• M-file: If you have a text file containing data, or you want to write a text file
containing data that you would eventually like to read in MATLAB , making it an
M-file may be an excellent option

 Excel Files (.xls, .xlsx):


Excel files are widely used for storing data in tabular format.
They can contain multiple sheets, rows, and columns.
MATLAB provides functions like xlsread , readtable , or
importdata to read data from Excel files into MATLAB. These
functions can read specific sheets, ranges of cells, or entire
spreadsheets.
Example: Reading data from the first sheet of an Excel file
named data.xlsx using xlsread :
[data, headers] = xlsread('data.xlsx', 'Sheet1');

Module-4
Q. 07 a How to name variables, what is the precision of computation and how to recall L3 5
previously typed commands?

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.

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 sub-window. We can double-click on any command in the
command history sub-window to execute it in the command window.
b With example explain input in matrices and vectors? L2 5

Page 01 of 02
BEC358B

OR
Q. 08 a Explain the steps in creating vector. L3 5

b Explain built-in functions of MATLAB. L2 5

Built-in functions in MATLAB are pre-defined functions provided by the


MATLAB software environment. These functions cover a wide range of
mathematical, statistical, signal processing, plotting, file input/output, and
other computational tasks. They are designed to simplify programming
tasks and enhance productivity by providing efficient and optimized
implementations of common operations.

MATLAB provides hundreds of built-in functions for numerical linear algebra,


data he p help analysis, Fourier transforms, data interpolation and r,urve fitting,
Page 01 of 02
BEC358B
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.
Examples:
sin(): Computes the sine of an angle in radians.
mean(): Computes the arithmetic mean of elements in an array.
plot(): Creates a 2D line plot.
fread(): Reads binary data from a file.
xlsread(): Reads data from an Excel file.
eye(): Creates an identity matrix.

Module-5
Q. 09 a Explain script files with example. L3 5

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.

A script file may contain any number of commands, including those that call built-
in functions or functions written by you. 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

-----(4.1)

b Explain function files with example L2 5

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 variales) ;

where the function_name must be the same as the file name (without the .m
extension) in which the function is written. For example, if the name of the
function is projecti le it must be written and saved in a file with the name
projectile.m.

Page 01 of 02
BEC358B

OR
Q. 10 a Explain 2 ways for executing a function. L3 5
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

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 semicolon 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. L2 5

Page 01 of 02

You might also like