1. CSE222: Basic Simulation lab Functions (MatLab)
Module 1: Creating a One-Dimensional Array (Row / Column Vector) Exercise β Creating a vector of even
whole numbers between 31 and 75; Creating a Two-Dimensional Array (Matrix of given size) and (A).
Performing Arithmetic Operations - Addition, Subtraction, Multiplication and Exponentiation. (B). Obtaining
Modified Matrix - Inverse, Transpose, with Appended and Deleted Elements;
Module 2: Performing Matrix Manipulations - Concatenating, Indexing, Sorting, Shifting, Reshaping, Resizing
and Flipping about a Vertical Axis/Horizontal Axis; Creating Arrays X & Y of given size (1 x N) and Performing
(A) Relational Operations - >, <, ==, <=, >=, ~=
(B) Logical Operations - ~, &, |, XOR
Functions:
1. Concatenation
C = [A B] horizontally concatenates matrices A and B
C = [A; B] vertically concatenates matrices A and B
For building a matrix horizontally, each component matrix must have the same number
of rows. When building vertically, each component must have the same number of columns.
C = cat(dim, A, B) concatenates the arrays A and B along array dimension dim.
C = cat(dim, A1, A2, A3, A4, ...) concatenates all the input arrays (A1, A2, A3, A4, and so on)
along array dimension dim.
C = horzcat(A1, A2, ...) horizontally concatenates matrices A1, A2, and so on
C = vertcat(A1, A2, ...) vertically concatenates matrices A1, A2, and so on
2. Indexing
A(m, :) give the all values of mth
row
A(:, n) give the all values of nth
column
3. Sorting
sort(matrix, dimension) Dimension argument 1 sorts matrix columns. Dimension argument 2 sorts
matrix rows.
B = sort(A) sorts the elements along different dimensions of an array, and arranges those
elements in ascending order.
B = sort(A, dim) sorts the elements along the dimension of A specified by a scalar dim.
B = sort(...,mode) sorts the elements in the specified direction, depending on the value of
mode.
'ascend' Ascending order (default)
'descend' Descending order
4. Shifting
B = circshift(A, shiftsize) circularly shifts the values in the array, A, by shiftsize elements
5. Reshaping and Resizing
B = reshape(A,m,n) returns the m-by-n matrix B whose elements are taken column-wise from
A. An error results if A does not have m*n elements.
B = reshape(A,m,n,p,...) or B= reshape(A,[m n p ...]) returns an n-dimensional array with the
same elements as A but reshaped to have the size m-by-n-by-p-by-.... The product of the specified
dimensions, m*n*p*..., must be the same as prod(size(A)).
B = rot90(A) rotates matrix A counterclockwise by 90 degrees.
B = rot90(A,k) rotates matrix A counterclockwise by k*90 degrees, where k is an integer.
6. Flipping
B = fliplr(A) returns A with columns flipped in the left-right direction, that is, about a vertical
axis.
2. B = flipud(A) returns A with rows flipped in the up-down direction, that is, about a horizontal
axis.
B = flipdim(A,dim) returns A with dimension dim flipped. When the value of dim is 1, the
array is flipped row-wise down. When dim is 2, the array is flipped columnwise left to right.
flipdim(A,1) is the same as flipud(A), and flipdim(A,2) is the same as fliplr(A).
7. Relational Operations
A < B A > B A <= B A >= B A == B A ~= B
The relational operators are <, >, <=, >=, ==, and ~=. Relational operators perform element-
by-element comparisons between two arrays. They return a logical array of the same size, with
elements set to logical 1 (true) where the relation is true, and elements set to logical 0 (false) where
it is not.The operators <, >, <=, and >= use only the real part of their operands for the
comparison. The operators == and ~= test real and imaginary parts.
8. Logical Operations
A & B A| B ~A
The symbols &, |, and ~ are the logical array operators AND, OR, and NOT. These operators
are commonly used in conditional statements, such as if and while, to determine whether or not
to execute a particular block of code. Logical operations return a logical array with elements set to
1 (true) or 0 (false), as appropriate.
xor(A,B) represents the logical exclusive disjunction. xor(A,B) is true when either A or B are
true. If both A and B are true or false, xor(A,B) is false.
Module 3: Generating a set of Commands on a given Vector (Example: X = [1 8 3 9 0 1]) to
(A) Add up the values of the elements (Check with sum)
(B) Compute the Running Sum (Check with sum), where Running Sum for element j = the sum of the
elements from 1 to j, inclusive.
(C) Compute the Sine of the given X-values (should be a vector).
Also, Generating a Random Sequence using rand() / randn() functions and plotting them.
Functions:
1. Sum
B = sum(A) returns sums along different dimensions of an array. If A is floating point, that is
double or single, B is accumulated natively, that is in the same class as A, and B has the same class as
A.
If A is not floating point, B is accumulated in double and B has class double.
If A is a vector, sum(A) returns the sum of the elements.
If A is a matrix, sum(A) treats the columns of A as vectors, returning a row vector of the sums of each
column.
If A is a multidimensional array, sum(A) treats the values along the first non-singleton dimension as
vectors, returning an array of row vectors.
B = sum(A,dim) sums along the dimension of A specified by scalar dim. The dim input is an integer
value from 1 to N, where N is the number of dimensions in A. Set dim to 1 to compute the sum of
each column, 2 to sum rows, etc.
B = cumsum(A) returns the cumulative sum along different dimensions of an array.
If A is a vector, cumsum(A) returns a vector containing the cumulative sum of the elements of A.
If A is a matrix, cumsum(A) returns a matrix the same size as A containing the cumulative sums for
each column of A.
If A is a multidimensional array, cumsum(A) works on the first nonsingleton dimension.
B = cumsum(A,dim) returns the cumulative sum of the elements along the dimension of A specified by
scalar dim. For example, cumsum(A,1) works along the first dimension (the columns); cumsum(A,2)
works along the second dimension (the rows).
3. 2. Sine function
Y = sin(X) returns the circular sine of the elements of X. The sin function operates element-
wise on arrays. The function's domains and ranges include complex values. All angles are in radians.
3. rand()
r = rand(n) returns an n-by-n matrix containing pseudorandom values drawn from the
standard uniform distribution on the open interval (0,1).
r = rand(m,n) or r = rand([m,n]) returns an m-by-n matrix.
r = rand(m,n,p,...) or r = rand([m,n,p,...]) returns an m-by-n-by-p-by-... array.
r = rand returns a scalar.
r = rand(size(A)) returns an array the same size as A.
4. randn()
r = randn(n) returns an n-by-n matrix containing pseudorandom values drawn from the
standard normal distribution.
r = randn(m,n) or r = randn([m,n]) returns an m-by-n matrix.
r = randn(m,n,p,...) or r = randn([m,n,p,...]) returns an m-by-n-by-p-by-... array.
r = randn returns a scalar.
r = randn(size(A)) returns an array the same size as A.
5. plot()
plot(Y) plots the columns of Y versus the index of each value when Y is a real number. For
complex Y, plot(Y) is equivalent to plot(real(Y),imag(Y))
Module 4: Evaluating a given expression and rounding it to the nearest integer value using Round,
Floor, Ceil and Fix functions; Also, generating and Plots of (A) Trigonometric Functions - sin(t), cos(t), tan(t),
sec(t), cosec(t) and cot(t) for a given duration βtβ. (B) Logarithmic and other Functions β log(A), log10(A), Square root
of A, Real nth
root of A.
Functions:
1. Round
Y = round(X) rounds the elements of X to the nearest integers. Positive elements with a fractional
part of 0.5 round up to the nearest positive integer. Negative elements with a fractional part of -0.5
round down to the nearest negative integer. For complex X, the imaginary and real parts are rounded
independently.
2. Floor
B = floor(A) rounds the elements of A to the nearest integers less than or equal to A. For complex
A, the imaginary and real parts are rounded independently.
3. Ceil
B = ceil(A) rounds the elements of A to the nearest integers greater than or equal to A. For complex
A, the imaginary and real parts are rounded independently.
4. Fix
B = fix(A) rounds the elements of A toward zero, resulting in an array of integers. For complex
A, the imaginary and real parts are rounded independently.
Example:-
a = [-1.9, -0.2, 3.4, 5.6, 7.0, 2.4+3.6i]
a = -1.9000 -0.2000 3.4000 5.6000 7.0000 2.4000 + 3.6000i
>> round(a)
ans = -2.0000 0 3.0000 6.0000 7.0000 2.0000 + 4.0000i
>> floor(a)
ans = -2.0000 -1.0000 3.0000 5.0000 7.0000 2.0000 + 3.0000i
>> ceil(a)
ans = -1.0000 0 4.0000 6.0000 7.0000 3.0000 + 4.0000i
>> fix(a)
4. ans = -1.0000 0 3.0000 5.0000 7.0000 2.0000 + 3.0000i
5. Square root
B = sqrt(X) returns the square root of each element of the array X. For the elements of X that are
negative or complex, sqrt(X) produces complex results.
6. Real nth
root
y = nthroot(X, n) returns the real nth root of the elements of X. Both X and n must be real and n
must be a scalar. If X has negative entries, n must be an odd integer.
Module 5: Creating a vector X with elements, Xn = (-1)n+1
/(2n-1) and Adding up 100 elements of the
vector, X; And, plotting the functions, x, x3
, ex
and exp(x2
) over the interval 0 < x < 4 (by choosing appropriate
mesh values for x to obtain smooth curves), on (A). A Rectangular Plot (B). A Semi log Plot (C). A log-log Plot
Module 6: Generating a Sinusoidal Signal of a given frequency (say, 100Hz) and Plotting with Graphical
Enhancements - Titling, Labelling, Adding Text, Adding Legends, Adding New Plots to Existing Plot, Printing
Text in Greek Letters, Plotting as Multiple and Subplots; Also, Making Non-Choppy and Smooth Plot of
the functions, f(x) = sin(1/x) for 0.01< x < 0.1 and g(x) = (sin x) /x.
Module 7: Creating a Structure, an Array of Structures and Writing Commands to Access Elements of the
created Structure and Array of Structures; Also, Solving First Order Ordinary Differential Equation using Built-
in Functions; And, Creating an M x N Array of Random Numbers using rand and setting any value that
is < 0.2 to β0β and any value that is β₯ 0.2 to β1β by moving through the Array, Element by Element.
Functions:
1. s = struct creates a scalar (1-by-1) structure with no fields.
2. s = struct(field,value) creates a structure array with the specified field and values.
Example:
Create a nonscalar structure with one field, f.
field = 'f';
value = {'some text';
[10, 20, 30];
magic(5)};
s = struct(field,value)
s =
3x1 struct array with fields:
f
View the contents each element.
s.f
ans =
some text
ans =
10 20 30
ans =
17 24 1 8 15
23 5 7 14 16
5. 4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
When you access a field of a nonscalar structure, such as s.f, MATLAB returns a comma-separated
list. In this case, s.f is equivalent to s(1).f, s(2).f, s(3).f.
3. s = struct(field1,value1,...,fieldN,valueN) creates a structure array
Example
Create a nonscalar structure with several fields.
field1 = 'f1'; value1 = zeros(1,10);
field2 = 'f2'; value2 = {'a', 'b'};
field3 = 'f3'; value3 = {pi, pi.^2};
field4 = 'f4'; value4 = {'fourth'};
s = struct(field1,value1,field2,value2,field3,value3,field4,value4)
s =
1x2 struct array with fields:
f1
f2
f3
f4
The cell arrays for value2 and value3 are 1-by-2, so s is also 1-by-2. Because value1 is a numeric array and not a
cell array, both s(1).f1 and s(2).f1 have the same contents. Similarly, because the cell array for value4 has a single
element, s(1).f4 and s(2).f4 have the same contents.
s(1)
ans =
f1: [0 0 0 0 0 0 0 0 0 0]
f2: 'a'
f3: 3.1416
f4: 'fourth's(2)ans =
f1: [0 0 0 0 0 0 0 0 0 0]
f2: 'b'
f3: 9.8696
f4: 'fourth'
4. s = struct([ ]) creates an empty (0-by-0) structure with no fields.
Module 8: Generating normal and integer random numbers (1-D & 2-D) and plotting them; Also,
Writing a Script (which keeps running until no number is provided to convert) that asks for Temperature
in degrees Fahrenheit and Computes the Equivalent Temperature in degrees Celsius. [Hint: Function is empty is
useful]
Module 9: Writing brief Scripts starting each Script with a request for input (using input) to Evaluate the
function h(T) using if-else statement, where
h(T) = (T β 10) for 0 < T < 100
= (0.45 T + 900) for T > 100.
Exercise: Testing the Scripts written using (A). T = 5, h = -5 and (B). T = 110, h = 949.5
Also, Creating a Graphical User Interface (GUI); And, Curve Fitting using (A) Straight line Fit (B). Least Squares
Fit.
6. Functions:
1. p = polyfit(x,y,n) finds the coefficients of a polynomial p(x) of degree n that fits the data, p(x(i)) to
y(i), in a least squares sense. The result p is a row vector of length n+1 containing the polynomial
coefficients in descending powers:
2. y = polyval(p,x) returns the value of a polynomial of degree n evaluated at x. The input argument p
is a vector of length n+1 whose elements are the coefficients in descending powers of the polynomial
to be evaluated.
y = p1xn
+ p2xnβ1
+ β¦+ pnx + pn+1
x can be a matrix or a vector. In either case, polyval evaluates p at each element of x.
Module 10: Interpolation based on following Schemes (A). Linear (B). Cubic (C). Spline Also, Generating
the first Ten Fibonacci numbers according to the relation Fn = Fn-1 + Fn-2 with F0 = F1 = 1, and Computing the
ratio Fn / Fn-1 for the first 50 Fibonacci numbers.
[Exercise: Verifying that the computed ratio approaches the value of the golden mean (1 + sqrt(5)) / 2 ]; Also
Generating Equivalent Square Wave from a Sine Wave of given Amplitude and Frequency; And,. Obtaining
the Covariance & Correlation Coefficient Matrices for a given Data Matrix.
Functions:
1. yi = interp1(x,Y,xi) interpolates to find yi, the values of the underlying function Y at the points in the
vector or array xi. x must be a vector. Y can be a scalar, a vector, or an array of any dimension, subject
to the following conditions:
a. If Y is a vector, it must have the same length as x. A scalar value for Y is expanded to have
the same length as x. xi can be a scalar, a vector, or a multidimensional array, and yi has the
same size as xi.
b. If Y is an array that is not a vector, the size of Y must have the form [n,d1,d2,...,dk], where n
is the length of x. The interpolation is performed for each d1-by-d2-by-...-dk value in Y. The
sizes of xi and yi are related as follows:
i. If xi is a scalar or vector, size(yi) equals [length(xi), d1, d2, ..., dk].
ii. If xi is an array of size [m1,m2,...,mj], yi has size [m1,m2,...,mj,d1,d2,...,dk].
Example:
Generate a coarse sine curve and interpolate over a finer abscissa.
x = 0:10;
y = sin(x);
xi = 0:.25:10;
yi = interp1(x,y,xi);
plot(x,y,'o',xi,yi)
2. yy = spline(x,Y,xx) uses a cubic spline interpolation to find yy, the values of the underlying function
Y at the values of the interpolant xx. For the interpolation, the independent variable is assumed to be
the final dimension of Y with the breakpoints defined by x. The sizes of xx and yy are related as
follows:
a. If Y is a scalar or vector, yy has the same size as xx.
b. If Y is an array that is not a vector,
i. If xx is a scalar or vector, size(yy) equals [d1, d2, ..., dk, length(xx)].
ii. If xx is an array of size [m1,m2,...,mj], size(yy) equals [d1,d2,...,dk,m1,m2,...,mj].
Example:
This generates a sine curve, then samples the spline over a finer mesh. x = 0:10;
y = sin(x);
xx = 0:.25:10;
yy = spline(x,y,xx);
plot(x,y,'o',xx,yy)