0% found this document useful (0 votes)
12 views39 pages

Programming With MATLAB

The document provides an overview of MATLAB, covering its applications, features, and working environment, as well as the MATLAB API and installation steps. It details the components of the MATLAB environment, differences between MATLAB and other programming languages, operators, and common toolboxes. Additionally, it explains how to run MATLAB code and includes information on built-in commands and variables.

Uploaded by

ahirawan7859
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)
12 views39 pages

Programming With MATLAB

The document provides an overview of MATLAB, covering its applications, features, and working environment, as well as the MATLAB API and installation steps. It details the components of the MATLAB environment, differences between MATLAB and other programming languages, operators, and common toolboxes. Additionally, it explains how to run MATLAB code and includes information on built-in commands and variables.

Uploaded by

ahirawan7859
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

Most important questions - Programming with

MATLAB (MCA 1st Sem)

Unit I (Introduction to MATLAB- Very Important)

1. What is MATLAB? Explain its applications , features and working


environment.

MATLAB (short for Matrix Laboratory) is a high-level programming language and


interactive environment developed by MathWorks for numerical computation, data
analysis, visualization, and algorithm development. It is primarily designed for
engineers and scientists to perform matrix manipulations, plot functions and data,
implement algorithms, create user interfaces, and interface with programs written in
other languages like C, C++, Java, and Python.

Applications:

★​ Engineering and Science: Used in signal processing, control systems, image


processing, computational biology, and financial modeling.
★​ Data Analysis: Handling large datasets, statistical analysis, and machine
learning.
★​ Simulation and Modeling: Through tools like Simulink for dynamic systems
simulation.
★​ Education: Teaching linear algebra, numerical methods, and programming
concepts.
★​ Industry: In automotive (e.g., vehicle dynamics), aerospace (e.g., flight
simulation), finance (e.g., risk assessment), and robotics.

Key Features:

●​ Matrix-based computations: Everything in MATLAB is treated as a matrix,


making it efficient for linear algebra operations.
●​ Built-in functions: Extensive library for math, statistics, signal processing,
optimization, etc.
●​ Toolboxes: Modular extensions for specific domains like image processing,
control systems, machine learning.
●​ Interactive environment: Command Window for immediate execution,
Workspace for variable management, and Editor for scripting.
●​ Graphics and visualization: Powerful plotting tools for 2D/3D graphs.
●​ Simulink integration: For modeling and simulating dynamic systems.
●​ Parallel computing support: Handles large datasets with GPU and multicore
processing.

1
●​ Cross-platform: Runs on Windows, macOS, Linux.

Working Environment:

➢​ Command Window: The primary interface for executing commands


interactively. You type commands here and see immediate results (e.g., a = 5; b
= 3; c = a + b outputs c = 8).
➢​ Workspace: Stores variables and their values. Use who or whos to view them.
➢​ Command History: Logs past commands for reuse.
➢​ Editor: For writing and debugging scripts (.m files).
➢​ Current Folder: Manages files and paths.
➢​ Toolstrip: Provides tabs for Home, Plots, Apps, etc., for quick access to
functions and toolboxes.
➢​ Help Browser: Integrated documentation via doc or help commands. The
environment is interactive, allowing rapid prototyping. MATLAB runs on
Windows, macOS, and Linux, with a focus on matrix-based operations where
arrays are fundamental data types.

2. Explain MATLAB API and steps to install MATLAB.

MATLAB API refers to the Application Programming Interface that allows integration
with external applications and languages. It includes:

❖​ MATLAB Engine API: For calling MATLAB from C/C++, Fortran, Python, Java,
or .NET. For example, in Python, you can use [Link] to start a MATLAB
session and execute code.
❖​ MATLAB Production Server: For deploying MATLAB code as web services.
❖​ Compiler SDK: To compile MATLAB code into standalone executables or
libraries.
❖​ ** Mex Files**: C/C++/Fortran functions callable from MATLAB for
performance-critical code.
❖​ Data APIs: For importing/exporting data (e.g., [Link] for XML/JSON).

Steps to Install MATLAB:

I.​ Acquire License: Purchase or get a trial from MathWorks website. Students
often get free access via university licenses.
II.​ Download Installer: Log in to MathWorks account, select the version (e.g.,
R2025b), and download the installer for your OS.
III.​ Run Installer: Double-click the installer file. Choose "Log in with a MathWorks
Account" or use a file installation key.
IV.​ Select Products: Choose MATLAB and desired toolboxes (e.g., Signal
Processing Toolbox).
V.​ Activate License: Enter your MathWorks account credentials or activation key.

2
VI.​ Install: Select installation folder (default is fine) and wait for completion (may
take 30-60 minutes).
VII.​ Verify: Launch MATLAB from the start menu or command line (e.g., matlab in
terminal). Check version with ver command.
VIII.​ Update Path: If needed, add MATLAB's bin folder to system PATH for
command-line access. Note: System requirements include 8GB RAM
minimum, and internet for activation.

3. Explain MATLAB environment (Command Window, Workspace, Editor).

The MATLAB environment consists of several integrated components for


development and execution:

●​ Command Window: This is the interactive console where you type commands
and see immediate results. It's like a REPL (Read-Eval-Print Loop). For
example, typing a = 5 + 3 and pressing Enter displays a = 8. It supports
command history (up/down arrows) and auto-completion.
●​ Workspace: A panel that displays all variables currently in memory, including
their names, values, sizes, and types. It's useful for inspecting data during
sessions. Variables persist until cleared (e.g., via clear command). For instance,
after assigning x = [1 2 3], Workspace shows x as a 1x3 double array.
●​ Editor: A text editor for writing and debugging scripts (.m files) and functions.
It includes syntax highlighting, debugging tools (breakpoints), and live error
checking. You can run scripts directly from here. For example, create a file
myscript.m with code, then type myscript in the Command Window to execute
it.

These components work together: Write code in Editor, run in Command Window,
and monitor variables in Workspace.

4. Difference between MATLAB and other programming languages (C, C++,


Python, Java)

Feature MATLAB C/C++ Python (with Java


NumPy)

Primary Numerical & General General General


purpose scientific purpose purpose purpose
computing

3
Speed of Very fast Slow Fast Medium
development

Execution Medium–Slow Very fast Medium–Fast Fast


speed (interpreted)

Syntax for Very simple Complex (need Simple with Complex


matrices arrays) NumPy

Built-in math Extremely rich Limited Rich (with Limited


functions libraries)

Graphics/Plott Excellent & Very difficult Good Difficult


ing very easy (matplotlib)

Cost Paid Free Free Free


(expensive)

5. What are MATLAB variables? Rules for naming variables.

Variables in MATLAB are containers for storing data like numbers, matrices, or
strings. They are dynamically typed (no need to declare type) and created upon
assignment, e.g., var = 10;.

Rules for Naming Variables:

●​ Must start with a letter (a-z, A-Z).


●​ Can include letters, digits (0-9), and underscores (_).
●​ Case-sensitive (e.g., Var and var are different).
●​ Cannot use reserved keywords (e.g., if, for, end).
●​ Maximum length: 63 characters (though shorter is recommended for
readability).
●​ Avoid starting with underscores for user variables (reserved for system use).
●​ Examples: Valid: myVar_1, dataMatrix. Invalid: 1var (starts with digit), my-var
(hyphen not allowed).

MATLAB overwrites variables if reassigned without warning.

4
6. List and explain operators in MATLAB.

MATLAB operators are symbols for performing operations on variables and values.
They are categorized as:

★​ Arithmetic Operators:
○​ +: Addition (e.g., 3 + 2 = 5).
○​ -: Subtraction (e.g., 5 - 2 = 3).
○​ *: Scalar multiplication (e.g., 3 * 2 = 6); for matrices, it's matrix
multiplication.
○​ /: Right division (e.g., 6 / 2 = 3); for matrices, solves linear equations.
○​ \: Left division (e.g., A \ B solves A * x = B).
○​ ^: Exponentiation (e.g., 2 ^ 3 = 8); for matrices, matrix power.
○​ .*, ./, .\, .^: Element-wise operations (e.g., [1 2] .* [3 4] = [3 8]).
★​ Relational Operators:
○​ ==: Equal to (e.g., 3 == 3 returns true).
○​ ~=: Not equal to.
○​ >, <, >=, <=: Greater/less than (or equal).
★​ Logical Operators:
○​ &: Element-wise AND.
○​ : Element-wise OR.
○​ ~: NOT.
○​ &&, ||: Short-circuit AND/OR (for scalars, evaluates only if necessary).
★​ Bitwise Operators (for integers):
○​ bitand, bitor, bitxor, etc.
★​ Assignment Operator:
○​ =: Assigns value (e.g., x = 5).

Operators follow precedence rules (e.g., ^ before *), and can be overloaded for custom
classes.

7. Difference between matrix operators and array operators.

●​ Matrix Operators (*, /, \, ^): For linear algebra (e.g., A * B requires compatible
dimensions for the matrix product).
●​ Array Operators (.*, ./, .\, .^): Element-wise (e.g., A .* B multiplies corresponding
elements; dimensions must match).

Example: For matrices A=[1 2;3 4], B=[5 6;7 8], A*B is a matrix product [19 22;43 50],
while A.*B is [5 12;21 32].

5
8. What is Simulink and LaTeX in MATLAB?

Simulink:

Simulink is a graphical programming environment integrated with MATLAB for


modeling, simulating, and analyzing multi-domain dynamical systems. It uses block
diagrams where blocks represent components (e.g., integrators, gains) connected by
lines for signal flow.

➢​ Applications: Control systems design, signal processing, embedded systems


(e.g., simulating a PID controller).
➢​ Key Features: Libraries of blocks, simulation modes (normal, accelerator), code
generation for hardware.
➢​ Usage: Launch with simulink; drag blocks, set parameters, run simulations.

LaTeX in MATLAB:

MATLAB supports LaTeX for formatting text in plots, GUIs, and documentation. It's
not a full LaTeX editor but integrates for mathematical expressions.

❖​ Usage: In plots, use 'Interpreter', 'latex' (e.g., title('$\int_0^1 x^2 dx$',


'Interpreter', 'latex') renders the integral).
❖​ Applications: Publishing reports with publish command, which converts .m
files to LaTeX-formatted PDFs.
❖​ Toolboxes: Live Editor supports inline LaTeX math.

9. Explain MATLAB Path and how to modify it.

The MATLAB Path is a list of folders where MATLAB searches for functions, scripts,
and classes when you call them. It's like the system's PATH but specific to MATLAB.
Default paths include installation directories and toolboxes.

How it Works:

★​ When you type myfunction, MATLAB searches the path top-to-bottom.


★​ Use path command to view the current path.
★​ which filename shows the full path of a file.

Modify the Path:

❖​ Temporarily:
➢​ addpath('folder/path'): Adds a folder to the top.
➢​ rmpath('folder/path'): Removes a folder.
➢​ pathtool: Opens GUI for editing.
❖​ Permanently:
➢​ Edit startup.m in userpath (runs on startup): Add addpath commands.

6
➢​ Use savepath after modifications via pathtool.
❖​ Best Practices: Avoid modifying core paths; use genpath for recursive
subfolders (e.g., addpath(genpath('myproject'))). Modifying ensures custom
scripts are accessible without full paths.

10. Difference between MATLAB and other programming languages.

●​ Matrix Focus: MATLAB treats everything as matrices by default (e.g., scalars


are 1x1 matrices), unlike languages like Python or C++ where arrays are
separate.
●​ Interpreted vs. Compiled: MATLAB is primarily interpreted (faster
prototyping), while C/C++ are compiled (faster execution).
●​ Syntax Simplicity: No need for loops for vectorized operations (e.g., A + B adds
matrices element-wise); Python requires NumPy for similar efficiency.
●​ Toolboxes and GUI: Built-in specialized libraries and easy GUI creation; Java
requires external libraries.
●​ Cost and Accessibility: MATLAB is proprietary and paid; open-source
alternatives like Octave mimic it but lack some advanced features.
●​ Performance: Slower for large loops compared to low-level languages, but
excels in numerical computations via optimized libraries.
●​ Applications: MATLAB for math-heavy tasks; general-purpose languages like
Python for web/apps.

11. Explain MATLAB help commands (help, doc, lookfor).

These commands provide documentation and search functionality:

●​ help: Displays brief documentation for a function or command in the


Command Window. Syntax: help function_name. Example: help sin shows
usage, description, and examples for the sine function.
●​ doc: Opens a detailed HTML help page in the Help Browser with examples,
algorithms, and related functions. Syntax: doc function_name. Example: doc
plot for plotting documentation.
●​ lookfor: Searches for keywords in the first line of help text across all functions.
Useful for discovery. Syntax: lookfor keyword. Example: lookfor matrix lists
functions like zeros, ones that mention "matrix".

These are essential for self-learning and troubleshooting.

7
12. What is get and set in MATLAB? List common MATLAB toolboxes.

get and set:

★​ get(handle): Retrieves properties of a graphics object (e.g., figure, axis).


Returns a structure with property names/values. Example: f = figure; get(f,
'Position') gets window position.
★​ set(handle, 'Property', Value): Sets properties. Example: set(gca, 'XLim', [0 10])
sets x-axis limits. These are used for customizing plots, GUIs, and objects
dynamically.

Common MATLAB Toolboxes:

➢​ Signal Processing Toolbox: For filtering, spectral analysis.


➢​ Image Processing Toolbox: For image enhancement, segmentation.
➢​ Statistics and Machine Learning Toolbox: For regression, clustering.
➢​ Control System Toolbox: For designing controllers.
➢​ Optimization Toolbox: For solving optimization problems.
➢​ Parallel Computing Toolbox: For GPU/multicore acceleration.
➢​ Simulink: For system simulation (extension, not just toolbox).
➢​ Deep Learning Toolbox: For neural networks.
➢​ Symbolic Math Toolbox: For symbolic computations.
➢​ Financial Toolbox: For portfolio analysis.

13. How to run MATLAB code?

❖​ Interactive Mode (Command Window): Type commands directly (e.g., x = 1:10;


sum(x)). Press Enter to execute.
❖​ Scripts (.m files):
➢​ Create in Editor: Write code, save as myscript.m.
➢​ Run: Type filename without .m (e.g., myscript) or use Run button.
❖​ Functions: Define in .m file (e.g., function y = myfunc(x)), call like myfunc(5).
❖​ Live Scripts (.mlx): Interactive with controls; run sections via Run Section.
❖​ From Command Line: matlab -r "myscript" (batch mode).
❖​ Debugging: Use breakpoints in Editor, dbstop, dbstep.
❖​ Apps/Toolboxes: Launch via appdesigner or specific commands. Ensure file is
on path; suppress output with semicolon ;.

14. Explain .m tools: who, whos, pi, eps, type.

These are built-in commands/variables:

★​ who: Lists variables in workspace (names only).


★​ whos: Detailed list (name, size, bytes, class, attributes). Example: who shows a
1x1 double.

8
★​ pi: Predefined constant ≈3.141592653589793 (e.g., circum = 2*pi*r).
★​ eps: Machine epsilon, smallest number such that 1 + eps ≠ 1 (≈2.2204e-16 for
doubles). Used for floating-point precision checks.
★​ type filename: Displays contents of .m file without running it (e.g., type
myscript.m prints code).

15. Explain elementary mathematical functions in MATLAB.

MATLAB provides built-in functions for basic math, operating element-wise on


arrays:

➢​ Trigonometric: sin(x), cos(x), tan(x), asin(x), etc. (in radians; use sind for
degrees).
➢​ Exponential/Logarithmic: exp(x) (e^x), log(x) (natural log), log10(x), sqrt(x).
➢​ Rounding: round(x), floor(x), ceil(x), fix(x) (towards zero).
➢​ Complex: abs(z) (magnitude), angle(z) (phase), real(z), imag(z), conj(z).
➢​ Hyperbolic: sinh(x), cosh(x).
➢​ Statistical: sum(A), mean(A), std(A), min(A), max(A).
➢​ Constants: Inf, NaN, i or j (imaginary unit). Example: sin(pi/2) = 1. These are
vectorized for efficiency.

16. Explain memory management functions in MATLAB.

MATLAB handles memory automatically (garbage collection), but functions help


optimize:

❖​ clear var: Removes variable from workspace, frees memory.


❖​ clear all: Clears all variables.
❖​ pack: Defragments memory (rarely needed in modern versions).
❖​ memory: Displays memory usage stats (MATLAB-specific).
❖​ inmem: Lists functions in memory.
❖​ mlock, munlock: Locks/unlocks functions in memory to prevent clearing.
❖​ For large data: Use sparse matrices (sparse), tall arrays, or matfile for partial
loading.
❖​ Monitoring: who shows bytes used. Best practice: Avoid global variables, use
functions for encapsulation.

17. Explain numeric data types in MATLAB.

MATLAB supports several numeric types for precision and memory efficiency:

●​ double: Default, 64-bit floating-point (e.g., 3.14). High precision for most
computations.
●​ single: 32-bit floating-point (e.g., single(3.14)). Less precise, saves memory.
●​ int8/uint8: Signed/unsigned 8-bit integers (-128 to 127 / 0 to 255).

9
●​ int16/uint16: 16-bit integers (-32,768 to 32,767 / 0 to 65,535).
●​ int32/uint32: 32-bit integers.
●​ int64/uint64: 64-bit integers for large numbers.
●​ logical: Boolean (true/false, stored as 1/0 uint8).

Or

Type Description Example syntax

double Default floating point 3.14159


(most used)

single 32-bit float single(3.14159)

int8/16/32/64 Signed integers int32(100)

uint8/16/32/64 Unsigned integers uint8(255)

logical true / false (1/0) true, false

char Character array (old style) 'Hello'

string Modern string (R2016b+) "Hello World"

cell Heterogeneous container {1, "text", [2 3]}

struct Structure with named [Link] = "Amit";


fields [Link]=101;

Conversion: Use functions like double(x), int32(x). Arrays can mix types but default to
double.

10
18. Difference between scalar, vector, and matrix.

●​ Scalar: Single value (1x1 matrix). Example: s = 5;. Operations apply directly.
●​ Vector: 1D array. Row vector: v = [1 2 3]; (1x3). Column vector: v = [1; 2; 3]; (3x1).
Accessed via indexing, e.g., v(2).
●​ Matrix: 2D array. Example: m = [1 2; 3 4]; (2x2). Supports element-wise and
matrix operations.

Key: Vectors/matrices enable vectorized operations (no loops needed), e.g., v * 2


doubles each element.

19. How to create a row vector and column vector?

matlab

% Row vectors

r1 = [1 2 3 4]; % method 1

r2 = 1:5; %12345

r3 = 0:0.5:3; % 0, 0.5, 1, ..., 3

r4 = linspace(0,10,5); % 5 equally spaced points

% Column vectors

c1 = [10; 20; 30];

c2 = (1:6)'; % transpose of row vector

20. Explain logical variables with examples.

Logical variables store true (1) or false (0) as uint8. Used for masking and conditions.

Example:

matlab

a = [1 2 3 4];

logicals = a > 2; % Results in [0 0 1 1] (false false true true)

a(logicals) = 0; % Sets a to [1 2 0 0]

Functions like and, or, not operate on them. Useful for conditional indexing.

11
21. How to create vectors in MATLAB?

●​ Row vector: v = [1 2 3]; or v = 1:3; (colon operator for increments).


●​ Column vector: v = [1; 2; 3]; or v = (1:3)'; (transpose).
●​ Linspace: v = linspace(0, 10, 5); % [0 2.5 5 7.5 10]
●​ Logspace: For logarithmic spacing.
●​ Empty: v = [];

22. How to create matrices in MATLAB?

●​ Direct: m = [1 2 3; 4 5 6; 7 8 9]; (3x3).


●​ Functions: zeros(2,3) (all zeros), ones(3) (square all ones), eye(3) (identity).
●​ Concatenation: m = [v1; v2]; for rows.
●​ Reshape: m = reshape(1:6, 2, 3); % 2x3 matrix.

23. Explain matrix addition, subtraction, multiplication.

●​ Addition/Subtraction: Element-wise, same dimensions. C = A + B; or C = A - B;.


●​ Multiplication: Matrix: C = A * B; (rows of A = columns of B). Element-wise: C =
A .* B;.

Example:

matlab

A = [1 2; 3 4];

B = [5 6; 7 8];

add = A + B; % [6 8; 10 12]

mult = A * B; % [19 22; 43 50]

24. What is the transpose of a matrix?

Transpose flips rows and columns. Syntax: B = A'; or B = transpose(A);.

Example: A = [1 2; 3 4] → A' = [1 3; 2 4]. For complex numbers, .' is non-conjugate


transpose.

25. Explain colon operator (:).

The colon operator creates sequences or selects ranges:

●​ Sequence: start:increment:end (default increment=1). E.g., 1:5 → [1 2 3 4 5].


●​ Indexing: A(:,2) (all rows, column 2).
●​ All elements: A(:) (column vector of all).

12
Example: m(2:3, :) selects rows 2-3, all columns.

26. Functions used for matrices: zeros, ones, eye.

●​ zeros(m,n): m x n matrix of zeros. E.g., zeros(2,3).


●​ ones(m,n): m x n matrix of ones.
●​ eye(n): n x n identity matrix (1s on diagonal, 0s elsewhere). E.g., eye(3).

Useful for initialization.

27. Explain MATLAB built-in functions.

Built-in functions are precompiled for efficiency, covering math, stats, etc. Examples:
sin, cos, exp, log, sqrt. Called like y = sin(x);. Vectorized for arrays.

28. Use of length, size, sum, mean.

●​ length(v): Number of elements in the vector (longest dimension for matrices).


●​ size(m): Array of dimensions, e.g., [rows cols] for 2D.
●​ sum(a): Sum of elements (column-wise for matrices).
●​ mean(a): Average (column-wise).

Example:

matlab

m = [1 2; 3 4];

size(m) % [2 2]

sum(m) % [4 6]

mean(m) % [2 3]

29. Explain max() and min() functions.

●​ max(a): Maximum value (column-wise max for matrices; returns values and
indices if two outputs).
●​ min(a): Minimum.

Example:

matlab

v = [3 1 4];

[maxVal, idx] = max(v); % maxVal=4, idx=3

13
30. Explain round, floor, ceil.

●​ round(x): Nearest integer (ties to even).


●​ floor(x): Largest integer ≤ x.
●​ ceil(x): Smallest integer ≥ x.

Example: round(3.6)=4, floor(3.6)=3, ceil(3.6)=4.

Unit II (Arrays & String- Most Important)

1. Define array in MATLAB. Explain multi-dimensional arrays, indexing &


addressing.

An array is a collection of elements arranged in a grid, fundamental in MATLAB


(everything is an array, even scalars are 1x1).

➢​ Types: Vectors (1D), matrices (2D), multi-dimensional (ND).


➢​ Creation: A = [1 2 3; 4 5 6] (2x3 matrix); B = zeros(2,3); C = rand(3).

Multi-dimensional Arrays:

➢​ Beyond 2D, e.g., 3D for images (RGB). Create: D = zeros(2,3,4) (2 rows, 3 cols, 4
pages).
➢​ Uses: Tensors in ML, volumetric data.

Indexing & Addressing:

★​ Linear: A(5) accesses 5th element (column-major order).


★​ Subscript: A(row,col) (1-based; e.g., A(2,3)).
★​ Colon Operator: A(:,3) (all rows, 3rd col); A(1:2, :) (rows 1-2, all cols).
★​ Logical: A(A > 5) returns elements >5.
★​ End Keyword: A(end) (last element).
★​ For ND: D(1,2,3).
★​ Addressing: Use find(A > 5) for indices.

2. What is a string in MATLAB? How is it created?

A string is a sequence of characters for text data. In modern MATLAB (R2016b+), use
double quotes: str = "Hello, World!";.

Creation Methods:

●​ Double quotes: s = "text"; (string array).


●​ Single quotes (legacy): c = 'text'; (char array).
●​ Concatenation: s = "Hello" + " " + "World";.
●​ Functions: string(array) converts other types.

14
●​ Arrays: strArray = ["apple", "banana"]; (1x2 string array).

Strings support operations like concatenation, substring extraction (e.g., str(1:5)), and
functions like upper, lower.

4. Explain string manipulation and string functions.

Strings are arrays of characters, created as 'text' or "text" (string array).

➔​ Manipulation: Concatenation strcat(s1,s2) or [s1 s2]; slicing s(1:3).


➔​ Functions:
◆​ length(s): Number of characters.
◆​ strcmp(s1,s2): Compare (case-sensitive; strcmpi insensitive).
◆​ strfind(s, pattern): Find substring positions.
◆​ strrep(s, old, new): Replace.
◆​ upper(s), lower(s): Case conversion.
◆​ split(s, delimiter): Split into cell array.
◆​ join(cellarray, delimiter): Join.
◆​ sprintf(format, vars): Formatted string.
◆​ For string arrays: contains, startsWith, extractBetween. Example: s =
"Hello World"; s = upper(s(1:5)) + s(6:end); gives "HELLO World".

5. What is interpolation and Extrapolation? Explain their types.


Interpolation: Estimating values within the range of known data points. Used for
smoothing or resampling.

Extrapolation: Estimating values outside the range, riskier due to assumptions.

Types:

➢​ Linear Interpolation: Straight line between points (interp1(x,y,xi,'linear')).


➢​ Cubic Spline: Smooth curves preserving derivatives ('spline').
➢​ Nearest Neighbor: Closest point ('nearest').
➢​ Polynomial: Fit polynomial (polyfit then polyval).
➢​ For 2D/ND: interp2, interp3, griddedInterpolant.
➢​ Extrapolation Methods: Same as above, but specify 'extrap' in interp1.

Example: x = 1:5; y = [1 4 9 16 25]; interp1(x,y,2.5,'linear') = 6.5 (between 4 and 9).

6. Write MATLAB programs for:

●​ Finding size of a matrix:​


matlab

A = [1 2 3; 4 5 6]; % Example matrix


[rows, cols] = size(A); % Get dimensions

15
disp(['Rows: ' num2str(rows) ', Columns: ' num2str(cols)]);
% Output: Rows: 2, Columns: 3

❖​ Concatenating matrices using cat():​


matlab

A = [1 2; 3 4];
B = [5 6; 7 8];
C = cat(2, A, B); % Concatenate horizontally (dim=2)
D = cat(1, A, B); % Vertically (dim=1)
disp(C); % [1 2 5 6; 3 4 7 8]
disp(D); % [1 2; 3 4; 5 6; 7 8]

❖​ Deleting a row or column:​


matlab

A = [1 2 3; 4 5 6; 7 8 9];
A(2,:) = []; % Delete 2nd row
A(:,3) = []; % Delete 3rd column
disp(A); % [1 2; 7 8]

❖​ Sorting array elements:​


matlab

A = [3 1 4 1 5 9];
sortedA = sort(A); % Ascending
[sortedA_desc, idx] = sort(A, 'descend'); % Descending with indices
disp(sortedA); % [1 1 3 4 5 9]
disp(sortedA_desc); % [9 5 4 3 1 1]

❖​ Matrix multiplication:​
matlab

A = [1 2; 3 4];
B = [5 6; 7 8];
C = A * B; % Matrix multiply
D = A .* B; % Element-wise
disp(C); % [19 22; 43 50]
disp(D); % [5 12; 21 32]

❖​ Sparse Matrix and its functions: Sparse matrices store only non-zero
elements for efficiency.​
matlab

A = sparse([1 2 3], [1 2 3], [10 20 30], 3, 3); % Create diagonal sparse


disp(A); % 3x3 sparse with non-zeros
fullA = full(A); % Convert to dense
nnz_count = nnz(A); % Number of non-zeros (3)
spy(A); % Visualize sparsity

16
7. Programs for: (Note: The original lists 4 items here)

★​ Plot a circle:​
matlab

theta = 0:0.01:2*pi;
x = cos(theta);
y = sin(theta);
plot(x, y);
axis equal;
title('Circle');

★​ Resize an image: Assuming an image file '[Link]':​


matlab

img = imread('[Link]');
resized = imresize(img, [100 100]); % Resize to 100x100
imshow(resized);
imwrite(resized, '[Link]');

★​ Read audio file:​


matlab

[audio, fs] = audioread('[Link]'); % Read file


sound(audio, fs); % Play
audiowrite('[Link]', audio, fs); % Write copy

★​ Generate sine wave:​


matlab

f = 440; % Frequency (Hz)


fs = 8000; % Sampling rate
t = 0:1/fs:1; % 1 second
sine = sin(2*pi*f*t);
plot(t, sine);
title('Sine Wave');
sound(sine, fs); % Play

Programs are compulsory from this unit, as noted.

17
Unit III (Control Statement , Scripts & Functions - Very
Important)

1. Explain loops in MATLAB.

Loops repeat code blocks. Types:

➢​ for Loop: Iterates over sequence.​


matlab

for i = 1:5

disp(i^2); % Prints 1,4,9,16,25

end

➢​ while Loop: Repeats while condition true.​


matlab

x = 1;

while x < 10

x = x * 2;

disp(x); % 2,4,8,16 (stops)

end

➢​ Nested Loops: Loops inside loops for multi-dimensional tasks.


➢​ Vectorization: Preferred over loops for speed (e.g., 1:5 .^2 instead of for loop).
Use break to exit early, continue to skip iteration.

2. Difference between for loop and while loop.

●​ for: Known iterations (e.g., over array). Index auto-increments.


●​ while: Unknown iterations; depends on condition (risk of infinite loop if not
updated).
●​ for: Simpler for sequences; while: For conditional continuation.

3. Difference between break and continue (with example).

❖​ break: Exits the loop entirely.


❖​ continue: Skips remaining code in current iteration, proceeds to next.

Example:

matlab

18
for i = 1:5

if i == 3

break; % Exits at 3, prints 1 2

end

disp(i);

end

for i = 1:5

if i == 3

continue; % Skips 3, prints 1 2 4 5

end

disp(i);

end

4. Difference between if and switch (with example).

➔​ if: Evaluates logical expressions, supports elseif/else for multiple conditions.


➔​ switch: Matches exact values (faster for many cases), uses case/otherwise.

Example:

matlab

x = 2;

if x == 1

disp('One');

elseif x == 2

disp('Two');

else

disp('Other');

end % Outputs 'Two'

19
switch x

case 1

disp('One');

case 2

disp('Two');

otherwise

disp('Other');

end % Outputs 'Two'

if is more flexible for ranges/inequalities; switch for discrete values.

5. Explain try/catch error handling.

Used for graceful error management:

★​ try: Executes code that might error.


★​ catch: Handles error if occurs.

Example:

matlab

try

result = 1 / 0; % Division by zero

catch ME

disp(['Error: ' [Link]]); % Outputs 'Error: Division by zero'

end

ME is an MException object with message, identifier, stack. Useful for robust scripts.

6. What is a function in MATLAB?

A function is a reusable block of code that accepts inputs, performs tasks, and returns
outputs. Defined in .m files.

20
7. How to create a user-defined function?

Create a .m file with function name matching filename.

Syntax:

matlab

function [out1, out2] = funcName(in1, in2)

% Code here

end

Example: File addTwo.m

matlab

function sum = addTwo(a, b)

sum = a + b;

end

Call: result = addTwo(3,4); % 7

Example program using function

File: calculateArea.m

matlab

function area = calculateArea(length, breadth)

area = length * breadth;

end

Call in script/command window:

matlab

a = calculateArea(5, 8); % a = 40

21
Or

Script file (.m) Function file (.m)

No function keyword Starts with function keyword

Runs in base workspace Has its own workspace

No input/output arguments Can have input & output arguments

Cannot be called with arguments Called by name with arguments

8. Difference between script file and function file.

●​ Script: .m file with commands; runs in base workspace (modifies global


variables). No inputs/outputs.
●​ Function: .m file starting with function; local workspace (variables scoped).
Accepts inputs, returns outputs.

Scripts for quick tasks; functions for modularity.

9. Explain function syntax in MATLAB.

●​ Start with function.


●​ Outputs in [] if multiple.
●​ Inputs in ().
●​ End with end (optional in single-function files).
●​ Comments after for help text.
●​ Can be anonymous: f = @(x) x^2; (inline).

10. Define function in MATLAB. Explain function syntax.

A function is a reusable code block that accepts inputs, performs tasks, returns
outputs.

●​ Types: Anonymous (f = @(x) x^2;), named in .m files.

Syntax (in .m file):

22
matlab

function [out1, out2] = funcName(in1, in2)

% Comments

out1 = in1 + in2;

out2 = in1 * in2;

end

❖​ First line: function keyword, outputs in [], name, inputs in ().


❖​ Body: Code.
❖​ Call: [sum, prod] = funcName(3,4); (sum=7, prod=12).
❖​ Varargin/varargout for variable args.

11. Explain Anatomy of an M-File function.

An M-File is a .m file containing a function or script.

➢​ Function Declaration: First executable line: function [outputs] = name(inputs).


➢​ Help Comments: Lines after declaration starting with % (displayed by help
name).
➢​ Body: Code, local variables.
➢​ Subfunctions: Additional functions in the same file, visible only internally.
➢​ Nested Functions: Functions inside functions, share variables.
➢​ End: Optional but good for clarity. Example structure in file myfunc.m:

matlab

function y = myfunc(x)

% MYFUNC Squares input.

y = x.^2;

end

12. Write program:

●​ Factorial using function:​


matlab

function fact = factorial(n)


if n == 0
fact = 1;
else
fact = n * factorial(n-1); % Recursive

23
end
end

% Call: factorial(5) = 120

●​ Roots of quadratic equation:​


matlab

function roots = quadRoots(a, b, c)


disc = b^2 - 4*a*c;
if disc < 0
roots = 'Complex';
else
roots = [-b + sqrt(disc)/(2*a), -b - sqrt(disc)/(2*a)];
end
end

% Call: quadRoots(1, -3, 2) = [2 1]

●​ Maximum of five numbers using function:​


matlab

function maxVal = maxFive(a,b,c,d,e)


maxVal = max([a b c d e]);
end

% Call: maxFive(1,5,3,4,2) = 5

Short + long answers both come, as noted.

13. Explain input() and disp() functions.

●​ input(prompt): Reads user input. E.g., name = input('Enter name: ','s'); ('s' for
string).
●​ disp(value): Displays value without 'ans ='. E.g., disp('Hello');.

14. Explain fprintf() function.

Formatted output to screen/file.

Syntax: fprintf(format, values);

●​ %d: integer, %f: float, %s: string, \n: newline.

Example: fprintf('Value: %d\n', 10); Prints "Value: 10"

24
15. How to take user input in MATLAB?

●​ input(): For keyboard input.


●​ uigetfile(): For file selection.
●​ GUI: Use inputdlg() for dialog boxes.

Example: age = input('Enter age: ');

Unit IV (Plotting & GUI - Very Important)

1. Explain M-File and MEX file.

M-File: Text file with .m extension containing MATLAB code (scripts or functions).
Executed interpretively. Example: Scripts run all code; functions are callable.

MEX File: Compiled C/C++/Fortran code with .mex extension (platform-specific, e.g.,
.mexw64). Faster for compute-intensive tasks.

★​ Create: Use mex filename.c to compile.


★​ Usage: Call like MATLAB function.
★​ Purpose: Performance boost, integrate legacy code.

2. Explain types of program files in MATLAB.

➔​ Script Files (.m): Sequence of commands, no inputs/outputs. Runs in base


workspace.
➔​ Function Files (.m): Start with function, local scope.
➔​ Live Scripts (.mlx): Interactive with output inline, supports controls.
➔​ MEX Files: Compiled for speed (see above).
➔​ P-Files (.p): Obfuscated .m files for IP protection (pcode file.m).
➔​ MAT-Files (.mat): Binary data storage (save, load).
➔​ Fig Files (.fig): Saved figures (savefig, openfig).
➔​ MLAPP Files (.mlapp): App Designer files for GUIs.

3. How to plot a graph in MATLAB?

➢​ Prepare data: e.g., x = 0:0.1:10; y = sin(x);.


➢​ Use the plotting function: plot(x,y).
➢​ Customize: title('Sine'), xlabel('x'), ylabel('y'), grid on;.
➢​ Multiple plots: hold on; plot(x,cos(x),'r--'); hold off;.
➢​ Save: print -dpng '[Link]'. Use figures for new windows.

25
4. Syntax of plot() function.

plot(x, y, 'options')

●​ x,y: Data vectors.


●​ Options: 'r--' (red dashed), 'bo' (blue circles).

Multiple: plot(x1,y1,x2,y2)

5. Explain xlabel, ylabel, title, grid.

●​ xlabel('text'): Labels x-axis.


●​ ylabel('text'): y-axis.
●​ title('text'): Plot title.
●​ grid on: Adds grid lines.

Example:

matlab

plot(x,y);

xlabel('Time');

ylabel('Amplitude');

title('Sine Wave');

grid on;

6. Explain 20 plots: (Note: Original says "20 plots", but lists 6; I'll explain
common 2D ones)

Common 2D plots (expanding to relevant):

❖​ plot(x,y): Line plot, connects points.


❖​ pie(data): Pie chart for proportions (e.g., pie([1 2 3])).
❖​ hist(data, bins): Histogram for distribution (e.g., hist(randn(1000),20)).
❖​ contour(X,Y,Z): Contour lines for 3D data on a 2D plane.
❖​ semilogx(x,y): Semi-log plot (log x-axis).
❖​ stairs(x,y): Stairstep graph for discrete data. Others: bar, stem, area, scatter,
errorbar, polarplot, loglog, semiology, fplot (functions), comet (animated),
pareto, boxplot, spy (sparsity), images (image).

26
7. Explain 30 plots: (Note: Original says "30 plots", lists 5; explaining
common 3D)

Common 3D plots:

★​ mesh(X,Y,Z): Wireframe surface.


★​ surf(X,Y,Z): Filled surface with color.
★​ meshz(X,Y,Z): Mesh with zero-plane skirt.
★​ cylinder(r): Generates cylinder surface.
★​ ribbon(x,y,width): Ribbon plot for trajectories. Others: contour3, surfc, meshc,
waterfall, slice (volumetric), streamline, quiver3, coneplot, ellipsoid, sphere,
pcolor, surfl (lighted), trisurf (triangulated), etc. Up to 30+ in toolboxes.

8. Explain 3D Visualization elements.

➔​ Surfaces: surf, mesh for gridded data.


➔​ Volumes: slice, isosurface for 3D datasets.
➔​ Vectors: quiver3 for field visualization.
➔​ Lighting/Camera: light, camlight, view(az,el) to set viewpoint.
➔​ Color Maps: colormap('jet') for shading.
➔​ Axes Properties: zlabel, zlim, axis equal.
➔​ Interaction: Rotate 3d tool for manual exploration. Example: [X,Y] =
meshgrid(-2:0.1:2); Z = X.^2 + Y.^2; surf(X,Y,Z);.

9. Difference between 2D plot and 3D plot.

●​ 2D: plot(x,y) for lines in the plane. Simple, for functions of one variable.
●​ 3D: plot3(x,y,z) for lines in space; mesh(x,y,z), surf(x,y,z) for surfaces. For
functions of two variables.

Example 3D:

matlab

[x,y] = meshgrid(-2:0.1:2);

z = x.^2 + y.^2;

surf(x,y,z);

10. How to create GUI in MATLAB?

Use App Designer or GUIDE (legacy).

App Designer Steps:

➢​ Launch: appdesigner.

27
➢​ Drag components: Buttons, axes, labels from Component Library.
➢​ Set properties: In Design View or Code View.
➢​ Add callbacks: Right-click component > Callbacks > Add (e.g.,
buttonPressedFcn).
➢​ Code: In Code View, write logic (e.g., plot([Link], x,y)).
➢​ Run: Click Run button.
➢​ Package: Export as .mlapp or standalone app. Example: Simple plot app with
button to generate sine wave.

Plot-related theory questions are sure.

11. Graph Customization in MATLAB

MATLAB provides extensive tools for customizing plots to make them


publication-ready, interactive, and visually appealing. Customization can be done
programmatically (via code) or interactively (via the figure toolstrip
introduced/expanded in recent versions).

Key Customization Techniques:

Basic Plot Creation and Line Properties

●​ Start with a plot, then customize lines using handles.​


matlab

x = 0:0.1:10;

y1 = sin(x); y2 = cos(x);

fig = figure;

p1 = plot(x, y1, 'b-', 'LineWidth', 2, 'Marker', 'o', 'MarkerSize', 6, 'MarkerFaceColor', 'r');

hold on;

p2 = plot(x, y2, 'r--', 'LineWidth', 1.5);

hold off;

●​ Axes, Labels, Title, Legend, Grid​


matlab

xlabel('Time (s)', 'FontSize', 12, 'FontWeight', 'bold');

ylabel('Amplitude', 'FontSize', 12);

title('Sine and Cosine Waves', 'FontSize', 14);

28
legend([p1 p2], 'sin(x)', 'cos(x)', 'Location', 'best', 'FontSize', 10);

grid on;

axis tight;

set(gca, 'FontName', 'Arial', 'FontSize', 11, 'Box', 'on', 'GridLineStyle', '--');

Color, Colormaps, and Shading

●​ Use colormap(jet) or custom like parula, viridis. For surfaces:​


matlab

[X,Y] = meshgrid(-5:0.5:5);

Z = sin(sqrt(X.^2 + Y.^2));

surf(X,Y,Z); shading interp; colormap('hot'); colorbar;

●​ Annotations, Text, Arrows​


matlab

annotation('textarrow', [0.6 0.7], [0.8 0.7], 'String', 'Peak', 'FontSize', 12);

text(5, 1, 'Maximum', 'Color', 'blue', 'FontWeight', 'bold');

●​ Modern Features (R2025+)


○​ New figure toolstrip for interactive editing (axes, legends, colors,
export).
○​ Dot notation for properties (faster than set/get): ax = gca; [Link] = [0
10];
○​ Better interactions: contextual pan/zoom per axes.
○​ tiled layout preferred over subplot for spacing/colorbars.

Best Practice

Use handles for objects, dot notation for speed, export with exportgraphics(fig,
'[Link]', 'Resolution', 300) for high-quality images.

12. Subplots in MATLAB

Subplots allow multiple plots in one figure. Two main approaches: classic subplot and
modern tiled layout (recommended since R2019b+ for better control).

Using subplot (Classic)

Syntax: subplot(m,n,p) → m rows, n columns, p-th position (1-based, row-major).

29
matlab

figure;

subplot(2,2,1); plot(1:10, sin(1:10)); title('Sine');

subplot(2,2,2); plot(1:10, cos(1:10)); title('Cosine');

subplot(2,2,[3 4]); plot(1:10, 1:10); title('Line (spans bottom)');

●​ Span multiple tiles: Use vectors like [3 4].

Using tiledlayout (Modern & Recommended)

Creates layout with better spacing, shared labels, colorbars.

matlab

figure;

t = tiledlayout(2,2, 'TileSpacing', 'compact', 'Padding', 'compact');

nexttile; plot(1:10, rand(1,10)); title('Random 1');

nexttile; plot(1:10, rand(1,10)); title('Random 2');

nexttile([1 2]); % Span 1 row, 2 columns

plot(1:10, 1:10); title('Full Bottom Row');

xlabel(t, 'X Axis (shared)', 'FontSize', 12);

ylabel(t, 'Y Axis (shared)', 'FontSize', 12);

●​ Flow layout: tiledlayout('flow') auto-arranges.


●​ Advantages: Shared axes labels, legends outside, better export.

Tip

Use tiledlayout for new code — it handles overlapping issues better and supports
modern features.

30
13. Symbolic Computation in MATLAB

Symbolic Math Toolbox enables exact (analytical) math, unlike numeric


floating-point.

Key Steps & Functions:

1.​ Create Symbols​


matlab

syms x y z a b c; % Multiple variables

f = a*x^2 + b*x + c; % Symbolic expression

2.​ Calculus
○​ Differentiation: diff(f, x) → 2*a*x + b
○​ Integration: int(sin(x), x) → -cos(x)
○​ Definite: int(x^2, x, 0, 1) → 1/3
○​ Limits: limit(sin(x)/x, x, 0) → 1
3.​ Solving Equations​
matlab

solve(a*x^2 + b*x + c == 0, x) % Quadratic formula

dsolve('Dy = y', y(0)==1) % Differential eq: y' = y → exp(x)

4.​ Simplification & Expansion​


matlab

simplify((sin(x)^2 + cos(x)^2)) % → 1

expand((x + y)^3) % → x^3 + 3x^2 y + 3x y^2 + y^3

factor(x^2 - 1) % → (x-1)(x+1)

5.​ Taylor Series & Plotting​


matlab

taylor(exp(x), x, 'Order', 5) % Up to x^4 term

fplot(sin(x)/x, [-10 10]); title('sinc(x)');

6.​ Substitution & Evaluation​


matlab

subs(f, {a,b,c}, {2, -3, 1}) % → 2x^2 - 3x + 1

double(subs(f, x, 2)) % Numeric value

31
Best Practice

Use syms for clarity. Convert to numeric with double or vpa (variable precision) when
needed. Great for derivation, proofs, and generating functions for numeric code.

14. Error Handling in MATLAB

Use try/catch to gracefully manage runtime errors (exceptions).

Basic Syntax:

matlab

try

% Risky code

result = 10 / 0; % Will error

disp(result);

catch ME % ME = MException object

disp('An error occurred!');

disp([Link]); % "Division by zero."

disp([Link]); % e.g., 'MATLAB:divideByZero'

% Optional: rethrow(ME); % Pass error up

end

Advanced Usage:

Specific Handling

●​ MATLAB doesn't allow multiple catch blocks like Java, so check identifier:​
matlab

try

load('[Link]');

catch ME

if strcmp([Link], 'MATLAB:load:couldNotReadFile')

disp('File not found - using default data.');

32
data = zeros(10);

else

rethrow(ME); % Let other errors propagate

end

●​ end

Nested try/catch

●​ Useful in functions for cleanup.


●​ Warnings as Errors​
matlab

warning('on', 'MATLAB:nearlySingularMatrix');

% or turn specific warning into error

●​ warning('error', 'MATLAB:singularMatrix');

Best Practices

●​ Use for file I/O, division, external data, hardware access.


●​ Always log errors (e.g., fprintf or diary).
●​ Clean up resources in catch (close files, reset variables).
●​ Avoid empty catch — always handle meaningfully.
●​ Prefer validation (if exist(...)) before risky operations.

Unit V (Linear Algebra - Very High Weight)

1. Define Linear Algebra. Explain Gaussian Elimination with the MATLAB


program.

Linear Algebra deals with vectors, matrices, linear transformations, and systems of
equations.

Gaussian Elimination: Method to solve Ax = b by transforming A to upper triangular


form via row operations (elimination), then back-substitution.

●​ Steps: Forward elimination (make below-diagonal zeros), backward


substitution.

Program:

33
matlab

function x = gaussElim(A, b)

n = length(b);

Ab = [A b]; % Augmented matrix

% Forward elimination

for k = 1:n-1

for i = k+1:n

factor = Ab(i,k) / Ab(k,k);

Ab(i,k:n+1) = Ab(i,k:n+1) - factor * Ab(k,k:n+1);

end

end

% Back substitution

x = zeros(n,1);

x(n) = Ab(n,n+1) / Ab(n,n);

for i = n-1:-1:1

x(i) = (Ab(i,n+1) - Ab(i,i+1:n)*x(i+1:n)) / Ab(i,i);

end

end

% Call: gaussElim([2 1; 4 3], [5; 13]) = [2; 1]

2. Explain linear equation functions:

●​ mldivide (A \ b): Solves Ax = b efficiently (uses LU/QR/Cholesky based on


matrix type). Preferred over inv.
●​ linsolve(A, b): Similar, but allows options (e.g., symmetric positive definite).
●​ inv(A): Matrix inverse (A^{-1}); multiply by b for solution. Avoid solving
systems due to numerical instability. Example: x = A \ b; is fast and accurate.

3. Define and explain:

●​ Eigen values: Scalars λ where Av = λv for matrix A, vector v ≠ 0. Represent


scaling factors.

34
●​ Eigen vectors: Non-zero vectors v satisfying above. Directions unchanged by
A.
●​ Characteristic matrix & Polynomial: Det(A - λI) = 0 is the characteristic
equation; polynomial is p(λ) = det(A - λI).

4. Programs to:

●​ Find Eigen values and Eigen vectors:​


matlab

A = [1 2; 3 4];

[V, D] = eig(A); % V: eigenvectors, D: diagonal with eigenvalues

disp(D); % Eigenvalues

disp(V); % Eigenvectors

5. Explain functions:

●​ eigs(A, k): Computes k largest eigenvalues/vectors (sparse/large matrices).


●​ svd(A): Singular Value Decomposition (USV'), S diagonal with singular values.
●​ eigs (repeated, same as above).

6. Define Curve Fitting and explain Curve Fitting Tools.

Curve Fitting finds mathematical models approximating data.

●​ Tools: Curve Fitting Toolbox (cftool), or functions like polyfit.


●​ cftool: GUI – import data, select model (polynomial, exponential), fit, evaluate.
●​ Functions: fit(x,y,'poly2') for quadratic; lsqcurvefit for nonlinear.
●​ Metrics: R-squared, residuals.

7. Explain with program:

●​ Differentiation: Numerical: diff(f(x)) / dx approx.​


matlab

syms x; % Symbolic

f = x^2 + sin(x);

df = diff(f, x); % 2x + cos(x)

●​ Integration:​
matlab

syms x;

35
f = x^2;

int_f = int(f, x); % (1/3)x^3

num_int = integral(@(x) x.^2, 0, 1); % 0.3333

●​ Data analysis:​
matlab

data = randn(100,1);

mu = mean(data);

sigma = std(data);

histogram(data);

Highest scoring unit.

Important MATLAB Programs (Very Important for Practical +


Theory)

Here are short, exam-favorite programs:

1.​ Addition of two matrices

matlab

A = [1 2; 3 4];

B = [5 6; 7 8];

C = A + B;

disp('Sum of matrices:');

disp(C);

2.​ Factorial of a number

matlab

n = input('Enter number: ');

fact = 1;

for i = 1:n

fact = fact * i;

36
end

fprintf('Factorial = %d\n', fact);

3.​ Fibonacci series

matlab

n = input('How many terms? ');

a = 0; b = 1;

fprintf('%d %d ', a, b);

for i = 3:n

c = a + b;

fprintf('%d ', c);

a = b;

b = c;

end

4.​ Check prime number

matlab

n = input('Enter number: ');

flag = 1;

for i = 2:sqrt(n)

if mod(n,i) == 0

flag = 0;

break;

end

end

if flag == 1 && n>1

disp('Prime');

else

37
disp('Not Prime');

end

5.​ Find largest of three numbers

matlab

a = input('a = '); b = input('b = '); c = input('c = ');

if a >= b && a >= c

disp(['Largest = ' num2str(a)]);

elseif b >= c

disp(['Largest = ' num2str(b)]);

else

disp(['Largest = ' num2str(c)]);

end

6.​ Sum of array elements

matlab

arr = [4 7 2 9 1 5];

sum = 0;

for x = arr

sum = sum + x;

end

disp(['Sum = ' num2str(sum)]);

% OR simply: sum(arr)

7.​ Simple plotting program

matlab

x = -10:0.5:10;

y = x.^2 - 4*x + 3;

plot(x,y,'r--','LineWidth',2);

38
xlabel('x'); ylabel('y');

title('Quadratic Function: y = x² - 4x + 3');

grid on;

Top 10 Most Important Questions (Exam Guaranteed)

These overlap with units; detailed answers above. Summarizing key points:

1.​ Explain MATLAB environment and applications.: See Unit I Q1.


2.​ Explain arrays and indexing in MATLAB.: See Unit II Q1.
3.​ Explain if, switch, loops with examples.: See Unit III Q1-3.
4.​ Explain user-defined functions in MATLAB.: See Unit III Q5.
5.​ Explain 2D and 3D plots in MATLAB.: See Unit IV Q3-5.
6.​ Explain Eigen values and Eigen vectors.: See Unit V Q3, Q4.
7.​ Write MATLAB program for Gaussian Elimination.: See Unit V Q1.
8.​ Explain Sparse Matrix.: Sparse stores only non-zeros with indices; efficient
for large, mostly zero matrices. See Unit II Q4 (last part).
9.​ Explain Curve Fitting in MATLAB.: See Unit V Q6.
10.​Explain M-File anatomy.: See Unit III Q6.

39

You might also like