ELEC1703-matlab代写-Assignment 1
时间:2022-11-15
ELEC1703 – Algorithms and
Numerical Mathematics
Function program; work with Arrays and Matrices in MATLAB – Assignment 1
School of Electronic &
Electrical Engineering
FACULTY OF ENGINEERING
ELEC1703 – Algorithms and Numerical Mathematics
Function program; work with Arrays and Matrices in MATLAB – Assignment 1
In ELEC1702 MATLAB Computer Lab sessions you have gained basic knowledge about MATLAB platform,
MATLAB syntaxes, flow charts, how to plot a function, looping, one dimensional arrays, how to make for or
while loop and use if-elseif ladder in simple algorithm. Now, in ELEC1703 we will move further, using
MATLAB to design simple MATLAB codes to be used for basic algorithms in numerical mathematics. In
ELEC1703 Assignment 1 we will introduce Function subroutine and further discuss Arrays in MATLAB this
time 2-dimensional arrays - matrixes.
Report format
This assignment is split into 3 parts, questions are shaded blue, while examples (if provided) are shaded grey.
- Answer all the questions in separate document (your report), include your name and student number.
- Make your report as organized as you can (e.g use tables for short questions, different colours, fonts
etc.). Assignment report template is provided on Minerva.
- For questions where you do something in MATLAB command line you must copy-paste input/output
from MATLAB to your report – you can do this directly (copy-paste) or take a print screen and paste
a picture.
- For questions which require you to write a code you should take a photo (snipping tool or print screen)
of your code in the report (or copy paste it) and also upload corresponding .m file along your report.
Also add comments into codes (using MATLAB symbol % ) and explain what lines in your code do in
the report.
- You should also add comments explaining what you did and notify anything you found peculiar in
MATLAB (and give an opinion why that happened).
- Only parts shaded in blue in this assignment need to be answered in your report. Grey shadings are
simply examples for you to familiarize with a topic.
- 5% of this assignment is the organization, make sure all .m files are uploaded on the Minerva, named
sensibly and cross-referenced in the report. Using the provided report template is recommended.
Contents
Function Files..........................................................................................................................................................3
Question 1 (20 marks).........................................................................................................................................4
Question 2 (40 marks).........................................................................................................................................6
Matrices in Matlab..................................................................................................................................................7
Inputting matrices................................................................................................................................................7
Matrix operations................................................................................................................................................8
Matrix types.........................................................................................................................................................9
Question 3. (35 marks)........................................................................................................................................9
Page 2 of 10
Dr D Indjin and Dr A. Demic
ELEC1703 – Algorithms and Numerical Mathematics
Function program; work with Arrays and Matrices in MATLAB – Assignment 1
Function Files
Functions are useful for complicated program to be broken down into smaller parts. Also If series of
statements is to be used many times
Syntax:
function [output variables]=function_name(input variables)
Statements describing function

end

Function file name is to be saved as function_name.m and the first executable statement must be “function”.
If there is more than one output value, one needs to put output variables in [] bracket. If there is only one
output variable the brackets are not necessary. Do not use input command within a function, since function
arguments are its inputs. Matlab does not have specifiers of data types for its variables, therefor if your
function operates with whole numbers (integers) you need to provide protection of the function in it.
Variables defined and manipulated inside the function subroutine are local to the function.
Please use Matlab help function in the command window to read more about syntaxes.
Example: Function for sum of n integer positive numbers
function mysum=my_sum_fun(n)
if (n<0)
error('Only positive input is accepted!')
end
if floor(n)~=n
error('Only integer values are accepted')
end
if numel(n)>1
error('Only single integer values are accepted, array/matrix input is prohibited')
end
mysum=0;
for i=1:n
mysum=mysum+i;
end
end
The first two if statements protect the function from negative and decimal input, and the third if statement
protects the function from an array/matrix input. Since Matlab does not have data type specifiers, unskilled
user may attempt sending illogical input to the function. Note that this can create a lot of execution problems,
for instance, for (or while) loop would not run correctly if n was an array or a matrix, however you will not get
an error message! The first iteration when i=1 will execute as mysum=mysum+1; and output of this function
will be mysum=1 with no error messages from Matlab! As a creator of the function you need to be very careful
and predict when you actually want your input to be an array and when not. Matlab has “dot” operators as ./
and .* to deal with the arrays which is useful when dealing with mathematical expressions, however if you
forget the dot, illogical output may occur with no errors on the screen! Generally “dot” operations simply save
you from writing a for loop that iterates through the array and performs * or / operation on each element.
Make sure you fully understand the usage of these operators.
Page 3 of 10
Dr D Indjin and Dr A. Demic
ELEC1703 – Algorithms and Numerical Mathematics
Function program; work with Arrays and Matrices in MATLAB – Assignment 1
Question 1 (20 marks)
1.1. Write down MATLAB function subroutines which defines the following functions (please make
separate .m file for each function):
f 1 ( x )=2 (sin x )
cos x
x
f 2 ( x )=e
xsin ⁡(x)
Write then the main MATLAB program, which evaluates functions for x between -2 and 2,
and plot the functions.
(10 marks)
1.2. If you check the MATLAB help page on plot function, you’ll discover numerous ways how to
set up your graphs by typing code. If you learn how to do this once, you can then copy paste
the set-up code for every future use when you need nicer graphs for your report (the default
behaviour of MATLAB’s plot function has very thin lines and very small font for example).
A better approach is to write a custom function that plots your data and contains such copy
paste code.
Construct a function that extends MATLAB’s plot function. The function needs to have at
least following arguments:
function z=better_plot(x,y,LineSpec,LineThickness,xlab,ylab,FontSize,enablegrid)
where x and y are data arrays that you wish to plot.
LineSpec is a string defining colour, marker and line type (same as in ordinary plot function)
LineThickness is a positive integer number - thickness of the data line you wish
xlab is a string describing the label of your x axis
ylab is a string describing the label of your y axis
FontSize is the size of font you wish to use for your axes
Enablegrid is a logical value that disables grid (0) or enables it (any numeric value that is not 0)
Test this function on data of your choice.
Note: Since MATLAB is defaulting data types, it is relatively difficult to validate if you user is really
sending input as string (word in single quotes as ‘word’. For simplicity, assume all input is valid, so
you do not need to worry about this, however do pay attention when testing the function, all string
arguments in this function need to be provided in single quotes and LineSpec variable needs to follow
syntax that MATLAB’s own LineSpec properties follow (check help page on plot function).
MATLAB is also not allowing to leave out a function argument (setting a default value behaviour is
complicated in MATLAB in comparison to C/C++ programming language), so even when you do not
wish to set some variable when using the function above, you still need to send empty string as the
argument (i.e empty quotes ‘ ’ )
(10 marks)
Page 4 of 10
Dr D Indjin and Dr A. Demic
ELEC1703 – Algorithms and Numerical Mathematics
Function program; work with Arrays and Matrices in MATLAB – Assignment 1
Example of how to use the function better_plot (that you need to create):
x=linspace(0,2*pi);
y=sin(x);
figure (1)
better_plot(x,y,'',5,'x','y',24,1)
figure(2)
better_plot(x,y,'-*r',7,'x','sin(x)',18,0)
Code output:
Figure 1: Figure 2:
Notice how all settings got applied, if you do not want some setting to apply, just pass empty string to
the function (as is was done for LineSpec for figure 1.
All settings for figure 2 got applied as instructed – Line spec is saying graph line should be red full
line with * as data markers, ylabel is saying sin(x), there is no grid, and font is smaller.
In both examples, this is still low plot quality as text on axes is hardly readable and data lines are too
thin, however depending on the size of figures you wish to place in the report, you can easily tweak
this function so it generates great figures. You can also add more plot settings, as setting text on
axes to be bold etc.
Note that if you wish some setting to always be applied and not controlled as function argument, you
can do that. Just do not pass as an argument, and define it in the function itself as all variables you
create in the function files are local (visible only in that function file). Also never name a variable in
your function the same as some variable that is passed as the function argument, because then you
would be overwriting the function argument.
In this way you can customize plot function settings however you like or need and this is very useful
in future whenever you need to create graphs for your reports!
Page 5 of 10
Dr D Indjin and Dr A. Demic
0 1 2 3 4 5 6 7
x
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
y
0 1 2 3 4 5 6 7
x
-1
-0.8
-0.6
-0.4
-0.2
0
0.2
0.4
0.6
0.8
1
si
n(
x)
ELEC1703 – Algorithms and Numerical Mathematics
Function program; work with Arrays and Matrices in MATLAB – Assignment 1
Question 2 (40 marks)
2.1. Construct a simple MATLAB function program my_factorial which calculates product of the
first n positive integer numbers (i.e. find factorial n!).
For full mark:
- Make sure you protect the code from illogical use (n must be positive integer)
- Test the function by comparing with built in MATLAB function factorial(n)
- Make sure you test your function for any limitations.
(10 marks)
2.2. Using my_factorial function from the previous subtask, construct new MATLAB function
program my_sin which evaluates sin ( x ) using Maclaurin expansion:
sin ( x )=x− x
3
3 !
+ x
5
5 !
− x
7
7 !
+ x
9
9 !
−…+…=x+∑
k=1
n
(−1 )k x
2k+1
(2k+1 )!
The number of terms n in this expansion needs to be provided by the user of the function as
an positive integer value and value of x must be a single numeric value and not an array or
matrix. Examine numerical limitations of this function and comment on their origin.
(10 marks)
2.3. Write a main MATLAB program in which you test the my_sin function from the previous
subtask by comparing with MATLAB built in function sin(x). Create a variable that represents
the numerical error (numerror=¿my sin−matlabsin∨¿) and then examine the effect of number of
terms in your my_sin function and the effect of x –axis you are using. You may find the
semilogy() command more useful than plot(). This displays the y-axis on a logarithmic
scale.
For full mark:
- Test your code for any limitations and comment on their origin
- If you discovered some limitations, make sure you protect the code from them.
(20 marks)
Note: Read more about numerical overflow. In MATLAB variables have double data type by default
and every time a function returns a value above or below the double data type range the
variable becomes ±Inf, for example exp(709)= 8.2184e+307 and exp(710)=Inf. The issue with
MATLAB is that it will not warn you about Infs and NaNs (not a number variable) and it is up
to the programmer to search for potential overflow and protect the code.
Hint: Function you need to create in 2.3 has two inputs: number_of_terms n and value of x. Both of
these should be single numeric values (positive integer and double data type). In order to
examine their effect you need to run your code for multiple values of x and number_of_terms.
We expect from you to do this automatically. The analytic approach is:
Page 6 of 10
Dr D Indjin and Dr A. Demic
ELEC1703 – Algorithms and Numerical Mathematics
Function program; work with Arrays and Matrices in MATLAB – Assignment 1
a) Fix x to some value, create array consisting of various number_of_terms and run a loop
calling your function for each value, calculate the numerical error, plot the numerical
error versus array of various numbers of terms and comment on your observations.
b) For examining effect of x, you should fix number_of_terms to some value, create array of
x values, run a loop for each value, calculate the numerical error, plot numerical error
versus array of x values and comment on your observations.
c) Finally, if you noticed some interlay of the effects you should repeat steps a) and b) by
changing the fixed terms or array range and then explaining how both parameters affect
your function at the same time, and what are the limitations.
Note that organization of your report will be marked. For question 1 (and any future questions where coding is
required) make sure that all your function files and main programme files are well organized and commented.
Do not forget to submit these on Minerva. In your report make sure you include a picture of your code when
referring to it (use snipping tool in Windows) and always comment on what you noticed and what happened,
especially if you noticed an issue and found a way to fix it (i.e. you realized your function breaks for inputs
larger then 100, and you added protection in it by using if statement with error function in MATLAB). Discuss
your plots and try linking the behaviour on them with the theoretical expectations. Your observations and
comments carry 20-50% of the mark.
Matrices in Matlab
Question 3 comprises easy questions to matrices in MATLAB and you can answer them without using .m files
and directly type on the command line. Make sure you take a screen shot of your input and output and in the
report, try organizing the answer neatly (i.e. use tables for short easy tasks).
Only parts shaded in blue in this assignment need to be answered in your report. Grey shadings are simply
examples for you to familiarize with a topic.
Inputting matrices
An array is effectively a row vector or a 1 x n matrix i.e.
>> rowvector = [3 5 7]
rowvector =
3 5 7
In MATLAB you can enter a n x 1 matrix (or column vector) using the following syntax
>> columnvector = [2;4;6]
columnvector =
2
4
6
Using the above information on inputting matrices as a starting point, enter the following matrices in MATLAB.
Page 7 of 10
Dr D Indjin and Dr A. Demic
ELEC1703 – Algorithms and Numerical Mathematics
Function program; work with Arrays and Matrices in MATLAB – Assignment 1
A=( 4 5 611 9 18 7 2)B=(1 2 37 8 9)
Matrix operations
You can carry out basic operations on matrices such as addition/subtraction and multiplication using MATLAB
but you need to be careful regarding the matrix dimensions. You can find out the matrix dimensions using the
size() command i.e.
>> size(A)
ans =
3 3
>> size(B)
ans =
2 3
Try and add A and B together. What happens? You should get an error message like the following:
>> A+B
??? Error using ==> plus
Matrix dimensions must agree.
You can only add matrices of the same size. Similarly if you try and multiply A and B, you will also get an
error:
>> A*B
??? Error using ==> mtimes Inner matrix dimensions must agree.
You have probably seen this error before when you accidently used the * (or /) operation instead of .* (or ./)
when using arrays. Remember, the dot . tells MATLAB to operate on the individual array elements rather than
the arrays as a whole. In this case, we are trying to multiply (3 x 3) x (2 x 3) matrices together. In this case,
our inner dimensions (underlined) are 3 and 2 and so they don’t agree and multiplication is not possible. What
happens if we multiply them in the opposite order?
>> B*A
ans =
50 44 14
188 170 68
This time we are doing (2 x 3) x (3 x 3) and so our inner dimensions agree. Remember that matrices in
general do not commute!
Multiplying by a scalar is much simpler i.e. we don’t have to worry about pre- or post-multiplication
>> 2*A
ans =
8 10 12
22 18 2
Page 8 of 10
Dr D Indjin and Dr A. Demic
ELEC1703 – Algorithms and Numerical Mathematics
Function program; work with Arrays and Matrices in MATLAB – Assignment 1
16 14 4
Matrix types
A diagonal matrix is a square matrix in which all elements are equal to zero apart from the main diagonal.
Suppose you want to enter a diagonal matrix you could do the following:
>> C = [6 0 0;0 3 0;0 0 9]
C =
6 0 0
0 3 0
0 0 9
What happens if you wanted to enter a 4 x 4, or a 100 x 100, or even a 1000 x 1000 diagonal matrix (which
can easily occur in some complex engineering problems)? This would very quickly get very messy.
Question 3. (35 marks)
(Each task is worth 5 marks).
3.1. Use the help files to find the command diag which makes it easier to enter diagonal matrices and use
it to produce a 5 x 5 diagonal matrix. (A n x n square matrix is also known as a square matrix of order
n).
The unit (or identity) matrix is a special case of diagonal matrix in which all the elements on the main diagonal
are equal to one.
3.2. Use the MATLAB help to find command eye do this and use it to produce a unit matrix of order 3. (If
you use the same command as you did to make the diagonal matrix you won’t get any marks!)
A zero (or null) matrix is a matrix in which all elements are equal to zero.
3.3. Use the MATLAB help to find command zeros to do this and use it to produce a 3 x 2 zero matrix.
(Again, if you use the same command as you did to make the diagonal matrix and set the diagonal to
be equal to zero you won’t get any marks!)

As the name suggests, a matrix of one’s is a matrix in which all the elements are equal to one. This is
sometimes called a unit matrix so make sure you don’t get it mixed up with an identity matrix!
3.4. Use the MATLAB help to find command ones to produce at matrix of ones and use it to produce a 2 x
4 unit matrix.
Matrix transpose
By interchanging the rows and columns in a matrix we obtain the matrix transpose.
3.5. Use the MATLAB help to find out how to calculate the transpose of a matrix A, (command A’ ) and
transpose the matrix A. Calculate A(AT). What do you notice about the resulting matrix?
Page 9 of 10
Dr D Indjin and Dr A. Demic
ELEC1703 – Algorithms and Numerical Mathematics
Function program; work with Arrays and Matrices in MATLAB – Assignment 1
A=( 4 5 611 9 18 7 2)
Matrix determinant and inversion
The determinant of a matrix A is a number and often denoted by |A| or det A.
Being able to invert a matrix allows us to do matrix division and allows us to solve systems of linear equations.
3.6. Find the determinant of A using the MATLAB help documents. Is A singular?
Calculate the inverse of a matrix A using the MATLAB help documents to find about command inv(A)
Solving systems of linear equations
We can write the following system of linear equations in matrix form
4 x1+5 x2+6 x3=8
11 x1+9x2+x3=15
8 x1+7x2+2 x3=12
( 4 5 611 9 18 7 2)(
x1
x2
x3)=(
8
15
12)
A x = b
If we know A-1 exists and the determinant of A is non-zero (i.e. A is non-singular) and so we know a
unique solution exists which can be found using x = A-1 b
3.7. Use MATLAB to calculate the values of x1, x2 and x3.
Hint: See Lecture 1 notes
Page 10 of 10
Dr D Indjin and Dr A. Demic


essay、essay代写