MatLab Unit 3 Questions with Answers
MatLab Unit 3 Questions with Answers
MatLab Unit 3 Questions with Answers
MATLAB has functions for computing exponents and logarithms for real and complex numbers.
Exponential Function:
o Command: exp(x)
o Description: Computes e^x, where e is the base of natural logarithms (approximately 2.7183).
o Example:
Base-10 Logarithm:
o Command: log10(x)
o Description: Computes the base-10 logarithm log10(x).
o Example:
Base-2 Logarithm:
o Command: log2(x)
o Description: Computes the base-2 logarithm log2(x).
o Example:
a) √ −144
Since √−144 involves the square root of a negative number, the result will be a complex number.
MATLAB Command:
Res=sqrt(-144);
disp(Res);
Result : 12i
b) e 3 y
MATLAB Command :
Y=[1 , 2] ;
res=exp(3 * y);
disp(res);
Explaination : The command exp(3 * y) calculates the exponential of each element in 3 * y, which
means it computes exp(3×1) and exp(3×2) for y = [1, 2]
C) log10(2y)
MATLAB Command :
Y=[1 , 2 , 3] ;
res=log10(2 * y);
disp(res);
Explaination : The command log10(2 * y) calculates the base-10 logarithm of each element in 2 *
y, which means it computes log10(2×1), log10(2×2), and log10(2×3) for y = [1, 2, 3]
d) log (-4x).
MATLAB Command :
X = 5;
res=log(-4 * x);
disp(res);
2. a. Explain how complex functions are handled by MATLAB. Give some examples.
In MATLAB, a complex function is any function or operation that can handle and manipulate complex
numbers, which have both real and imaginary parts. Complex numbers in MATLAB are represented as
a+bi or a+bj, where a is the real part, b is the imaginary part, and i or j represents the imaginary unit
(equivalent to √ −1 ).
Syntax: z = a + bi or z = complex(a, b)
Here are some common functions and examples that demonstrate how MATLAB handles
complex functions:
1. abs – Absolute Value (Magnitude)
The abs function in MATLAB returns the magnitude (or modulus) of a complex number, which is
the distance from the origin to the point in the complex plane.
Example:
z = 3 + 4i;
magnitude = abs(z); % Result: magnitude = 5
The angle function returns the phase angle (or argument) of a complex number, which is the
angle in radians between the positive real axis and the line connecting the origin to the point.
Example:
z = 3 + 4i;
theta = angle(z); % Result: theta ≈ 0.9273 radians
The real function extracts the real part of a complex number, while imag extracts the imaginary
part.
Example:
z = 5 - 2i;
real_part = real(z); % Result: real_part = 5
imaginary_part = imag(z); % Result: imaginary_part = -2
Definition: The round function rounds a number to the nearest integer. If the fractional part of the
number is exactly 0.5, MATLAB rounds to the nearest even integer.
Syntax: round(x)
Examples:
->x = 3.6;
y = round(x); % Result: y = 4
-> x = 3.4;
y = round(x); % Result: y = 3
Definition: The ceil function rounds each element of x to the nearest integer greater than or equal to that
element, also known as rounding up.
Syntax: ceil(x)
Examples:
->x = 2.1;
y = ceil(x); % Result: y = 3
->x = -1.7;
y = ceil(x); % Result: y = -1
Here, -1.7 is rounded up to -1, as it’s the nearest integer greater than -1.7.
Definition: The floor function rounds each element of x to the nearest integer less than or equal to that
element, also known as rounding down.
Syntax: floor(x)
Examples:
->x = 2.9;
y = floor(x); % Result: y = 2
->x = -3.2;
y = floor(x); % Result: y = -4
Here, -3.2 is rounded down to -4, the nearest integer less than -3.2.
Course Code: 20EC0454 R20
3. a. Explain how Trigonometric Functions and Hyperbolic Functionsare handled by MATLAB. Give
some examples.
MATLAB provides a wide range of trigonometric and hyperbolic functions that can operate on real and
complex numbers.
Trigonometric functions in MATLAB include sine (sin), cosine (cos), tangent (tan), and their inverses
(asin, acos, atan, etc.).
1. Sine Function
x = pi / 2;
y = sin(x); % Result: y = 1
2. Cosine Function
matlab
Copy code
x = pi;
y = cos(x); % Result: y = -1
3. Tangent Function
x = pi / 4;
y = tan(x); % Result: y = 1
Copy code
x = 0.5;
angle_sin = asin(x); % Result: angle_sin ≈ 0.5236 radians (30 degrees)
These functions return the value of given degree for a trigonometric ratio.
Syntax: sind(x),cosd(x),tand(x),asind(x)
Example:
Course Code: 20EC0454 R20
x = 90;
y = sind(x); % Result: y = 1
Hyperbolic functions include hyperbolic sine (sinh), hyperbolic cosine (cosh), hyperbolic tangent
(tanh), and their inverses (asinh, acosh, atanh).
x = 1;
y = sinh(x); % Result: y ≈ 1.1752
x = 1;
y = cosh(x); % Result: y ≈ 1.5431
x = 1;
y = tanh(x); % Result: y ≈ 0.7616
These functions return the hyperbolic angle corresponding to a given hyperbolic ratio.
x = 1;
angle_sinh = asinh(x); % Result: angle_sinh ≈ 0.8814
b) For several values of x in the range 0 ≤x ≤5, confirm that sin(ix)= isinhx..
Course Code: 20EC0454 R20
a) Verifying tan(2x)=2tan(x) / 1−tan^2(x) for 0≤ x ≤20 .
This identity can be checked by defining a vector of values for xxx within the range and calculating both
the left-hand side (tan(2*x)) and the right-hand side (2 * tan(x) / (1 - tan(x)^2)).
Matlab code:
end
In this identity, iii is the imaginary unit, and xxx is a real number. To test this, we can calculate the left-
hand side (sin(i*x)) and the right-hand side (i * sinh(x)) for several values of x between 0 and 5.
end
In MATLAB, a user-defined function is a custom function created by the user to perform specific
operations or calculations. Unlike built-in functions, these are saved as separate files with the extension
.m, and can be called by their file name to perform their defined tasks. User-defined functions help
organize code, avoid repetition, and make programs easier to maintain.
Example 1:
This function calculates the square of a number. Save the function as squareNumber.m.
% Main script
x = 4;
output = squareNumber(x);
disp(output); % Output will be 16
Example 2:
This function takes two numbers and returns their sum. Save this function as addNumbers.m.
% Main script
a = 5;
b = 3;
output = addNumbers(a, b);
disp(output); % Output will be 8
Minimizing a function of one variable involves finding the point at which the function takes its
smallest value over a given interval or domain. This process is common in optimization, where
we seek the minimum of a function f(x) over an interval [a,b]. In MATLAB, this is typically
done using numerical methods like fminbnd.
The function fminbnd in MATLAB is specifically designed to find the minimum of a single-variable
function over a specified interval.
Syntax:
x_min = fminbnd(@functionName, a, b);
Expected Output:
Minimum occurs at x = 3
Minimum value is f(x) = 5
5. a. Compute the area A and circumference C of a circle, given its radius(r=4) as an input
argument.
To calculate the area A and circumference C of a circle given its radius r=4, we can use the following
formulas:
Area: A=πr^2
Circumference : C =2πr
MATLAB Code
Main Script :
r = 4;
[A, C] = circleProperties(r);
Output :
1. Reusability : Functions can be used multiple times, saving time and reducing redundancy.
2. Readability : Code is easier to read and follow by breaking it into modular pieces.
3. Simplified Debugging : Functions can be tested individually, simplifying error-finding.
Course Code: 20EC0454 R20
4. Reduced Code Length : Calling functions avoids repetitive code, making scripts shorter.
5. Scalability : Functions make it easy to add or modify features as projects grow.
6. Encapsulation : Functions encapsulate specific tasks, hiding implementation details for better
abstraction.
Local Variables
Definition: Variables that are defined within a function and are only accessible within that specific
function.
Scope: Limited to the function in which they are defined. They cannot be accessed or modified outside that
function.
Example:
function myFunction()
x = 10; % Local variable
disp(x);
end
Global Variables
Definition: Variables that can be accessed and modified from any function or workspace in MATLAB,
provided they are declared as global in each context they are used.
Scope: Available across different functions or workspaces where they are explicitly declared as global.
Usage: To use a global variable in MATLAB, declare it with the keyword global in each function or
workspace where you want to access it.
Example:
function modifyGlobal()
global y; % Declare global in this function too
y = y + 5;
end
Here, y is a global variable and can be accessed and modified by any function or workspace where it's
declared as global.
In MATLAB, there are several ways to call functions, depending on the function type as follows :
MATLAB has a large library of built-in functions, such as sin, cos, mean, sum, and others, which can be
called directly with the required input arguments.
Example :
result = mean([1, 2, 3, 4, 5]);
Course Code: 20EC0454 R20
Here, mean is a built-in function, and you call it by passing in an array as an argument.
Functions created by the user can be saved as separate .m files and then called in the script or command
window. Each .m file should be named after the function it defines.
A nested function is defined within another function, and it has access to the variables of the outer
function. Nested functions are helpful for tasks that require helper functions.
Example :
function mainFunction()
x = 10;
disp(nestedFunction(x));
function y = nestedFunction(x)
y = x^2;
end
end
4. Calling Subfunctions
Subfunctions are additional functions defined within the same .m file as the main function but outside of
its main body. Subfunctions can only be called by the main function or other subfunctions within the
same file.
Anonymous functions are functions that are defined in a single line using the @ symbol. They are often
used for short, simple operations and can be called directly or passed as arguments.
Example :
square = @(x) x^2;
result = square(5); % Output will be 25
7. What is mean by functions? Explain various types functions in MATLAB with suitable
example.
Course Code: 20EC0454 R20
Function :
In MATLAB, functions are self-contained blocks of code designed to perform specific tasks. They take
inputs, process them, and return outputs. Functions help in organizing code, improving readability, and
reusability. MATLAB has several types of functions, including built-in functions, user-defined functions,
anonymous functions, nested functions, variable argument lists, private functions, and subfunctions.
1. Built-in Functions
These are predefined functions provided by MATLAB for various mathematical and engineering
operations.
Syntax:
output = builtInFunction(input)
Example:
% Using the built-in function 'sqrt' to calculate the square root of a number
result = sqrt(16);
disp(result); % Output: 4
2. User-defined Functions
User-defined functions are created by the user to perform specific tasks. They can take input arguments
and return output values.
Syntax:
Example:
3. Anonymous Functions
Anonymous functions are one-line functions defined without a separate file. They are useful for simple
operations and can be created using the @ symbol.
Syntax:
f = @(input) expression
Example:
4. Nested Functions
Nested functions are defined within another function. They can access variables from the parent
function's workspace.
Syntax:
Example:
5. Private Functions
Private functions are defined in a separate file and are only accessible to functions in the same directory
or in subdirectories. They are useful for encapsulating functionality that should not be exposed to users of
your primary function or module.
Syntax:
% In 'myFunction.m'
function output = myFunction(x)
output = privateFunction(x); % Call the private function
end
6. Subfunctions
Subfunctions are functions defined within the same file as another function. They can only be called by
the main function in that file or other subfunctions defined in the same file. Subfunctions are useful for
organizing code related to a primary function without making them accessible outside of that context.
Syntax:
Example of Subfunction:
result = mainFunction(4);
disp(result); % Output: 16
Anonymous Functions
Anonymous functions are one-line functions defined without a separate file. They are useful for simple
operations and can be created using the @ symbol.
Syntax:
f = @(input) expression
Example:
In MATLAB, anonymous functions can handle multiple input arguments using the same syntax as regular
functions. The key is to define the function using a single variable for all inputs and then use that variable
as needed within the function body. Here's how it works:
To create an anonymous function that accepts multiple input arguments, use the following syntax:
create an anonymous function that takes two inputs and performs a mathematical operation.
% Define an anonymous function that takes two inputs and returns their sum
sumFunction = @(x, y) x + y;
Anonymous functions can also handle array inputs. In this case, the function operates element-wise on
arrays.
Nested functions are defined within another function. They can access variables from the parent
function's workspace.
Syntax:
Example:
Course Code: 20EC0454 R20
% Define a function 'outerFunction' with a nested function 'innerFunction'
function outerFunction()
a = 5; % Variable in the outer function
% Define the nested function
function b = innerFunction()
b = a + 10; % Accessing variable 'a' from the outer function
end
result = innerFunction(); % Call the nested function
disp(result); % Output: 15
end
Private Functions :
Private functions are defined in a separate file and are only accessible to functions in the same
directory or in subdirectories. They are useful for encapsulating functionality that should not be
exposed to users of your primary function or module.
Syntax:
% In 'myFunction.m'
function output = myFunction(x)
output = privateFunction(x); % Call the private function
end
In MATLAB, importing data from Excel files or using the Import Wizard is by the following methods:
1. Importing Wizard:
Accessing the Wizard: You can start the Import Wizard by selecting Import Data from the Home tab in
the MATLAB toolstrip or by using the uiimport command in the command window.
File Selection: The wizard allows you to browse for a file (e.g., .csv, .txt, .xls).
Course Code: 20EC0454 R20
Data Preview: Once a file is selected, you can see a preview of the data, where you can choose which
variables to import and how to format them.
Options: You can set options such as specifying delimiters, selecting variable names, and handling missing
data.
Importing: After configuring the settings, you can import the data into the MATLAB workspace as a table
or array.
Using readtable or readmatrix: You can directly import Excel files using these functions. For
example:
o data = readtable('filename.xlsx'); imports data as a table.
o data = readmatrix('filename.xlsx'); imports data as a numeric matrix.
Specifying Sheets and Range: You can specify the sheet name and range within the file:
Handling Different Data Types: MATLAB automatically detects and converts different data types in the
Excel file, making it easy to work with mixed data.
Exporting ASCII data files in MATLAB can be done using several functions, depending on specific
needs and the format we want by the following ways:
1. Using writematrix
2. Using writetable
4. Using fprintf