WrittenReport02
docx
keyboard_arrow_up
School
University of Utah *
*We aren’t endorsed by this school
Course
3200
Subject
Computer Science
Date
Apr 3, 2024
Type
docx
Pages
20
Uploaded by UltraRoseArmadillo41
CS 3200-001
Spring 2024
Instructor:
Martin Berzins
Duke Nguyen
u1445624
February 13, 2024
Assignment #2 – Written Report
(Due date
: February 11, 2024 by 11:59PM)
What to turn in:
For the assignments, we expect both SOURCE CODE
and a written
REPORT be uploaded as a zip or tarball file to Canvas.
•
Source code for all programs that you write, thoroughly documented.
o
Include a README file describing how to compile and run your code.
•
Your report should be in PDF format and should stand on its own.
o
It should describe the methods used.
o
It should explain your results and contain figures.
o
It should also answer any questions asked above.
o
It should cite any sources used for information, including source code.
o
It should list all of your collaborators.
This homework is due on February 11
th
at 11:59 pm. If you don't understand these directions, please feel free to email the TAs or come see one of the TAs or the instructor during office hours well in advance of the due date.
1
Problem 1:
Question 5.10 of Cleve Moler’s book
(50 points)
I initially sort a set of (x, y) data points in ascending order of their x-values and then to
create a scatter plot of these sorted points. This line sorts the rows of the matrix yy based on the
values in its second column. The matrix yy is assumed to contain data points, with each row
representing a point. The second column likely contains the x-values of these points. After this
line, yy will be rearranged so that its rows are in ascending order of the x-values.
% Sort the data based on x values
sortrows(yy, 2);
sorted_x = yy(:, 2);
sorted_y = yy(:, 1);
% Plot the sorted data
figure;
plot(sorted_x, sorted_y, '*'
);
xlabel(
'x'
);
ylabel(
'y'
);
title(
'Sorted and Plotted Data'
);
grid on
;
2
(a)
(10 points)
As your first experiment, use the code to read this data file and sort it and
plot it . You should see something like the figure of sample output below.
The first line sorts the rows of the matrix yy based on the values in its second column.
The matrix yy is assumed to contain data points, with each row representing a point. The second
column likely contains the x-values of these points. After this line, yy will be rearranged so that
its rows are in ascending order of the x-values. The next two lines extract the second and first
column of the now-sorted matrix yy and stores it in the variable sorted_x and sorted_y
respectively. Those columns represent the x and y-values of the data points, now in sorted order.
Use the plot method, a graph is obtained as below:
Figure 1.1:
A graph plotting the given data after being sorted
3
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Using the formula above, the sorted data points are now scaled in the range [-1,1] by
using the below snipper of codes.
% Linear scaling for x and y
x_min = min(sorted_x);
x_max = max(sorted_x);
y_min = min(sorted_y);
y_max = max(sorted_y);
scaled_y = (2 * sorted_y) / (y_max - y_min) - (y_max + y_min) / (y_max - y_min);
scaled_x = (2 * sorted_x) / (x_max - x_min) - (x_max + x_min) / (x_max - x_min);
Hence, we will obtain an updated version of the graph.
Figure 1.2:
A graph plotting the same data set after being sorted and scaled
4
(b)
(10 points)
Use a linear scaling to put both x and y values in the range [-1,1] such as
y
i
=
2
(
y
max
−
y
min
)
y
i
−
(
y
max
+
y
min
)
(
y
max
−
y
min
)
The below code is structured to execute polynomial fitting at varying degrees,
specifically for degrees 5, 10, 15, 20, and 25. It caters to a dataset containing 82 points, with the
data already scaled to fit within the range of -1 to 1. The process involves creating a
Vandermonde matrix for each polynomial degree, which is then used to perform least squares
fitting on the scaled data. This fitting process computes the polynomial coefficients that best
approximate the scaled data in a least squares sense.
For each polynomial degree, it evaluates the fitted polynomial over a collection of 1001
points in range from -1 to 1. This evaluation helps visualize how well the polynomial fits the data
across this range. The results are plotted, showing both the original data points and the
corresponding polynomial fit, thus providing a clear visual representation of the fitting quality. % Degree of the polynomial
m_values = [5, 10, 15, 20, 25];
n = 82; % Number of data points
% Evaluate the polynomial at 1001 points
xplot = linspace(-1, 1, 1001);
% Loop over each degree m
for m = m_values
5
(c)
(20 points)
Write a program that uses the Monomial Vandermode matrix
approximation to produce a least squares approximation to work with this data set. In
this case n
= 82 as there are 82 data points and m is the degree of the polynomial with
m + 1
terms. Use values of m
equal to 5, 10, 15, 20, 25. Plot the values of the
polynomial by evaluating the Vandemonde polynomial at (say) 1001 points and use
plots to show how the different polynomials behave. Contrast the visual appearance of
the polynomial in each of the five cases m
= 5, 10, 15, 20, 25. Use the supplied
regression code on the canvas page as a model if you find that helpful. An easier option is to use the matlab functions polyfit
and polyval
. If you
use these you will not be able to estimate the condition numbers of the matrices.
Instead MATLAB will tell you that the matrix is ill-conditioned.
% Create Vandermonde matrix for fitting
A = ones(n, m+1);
for j = 2:m+1
A(:, j) = scaled_x.^(j-1);
end
% Perform least squares fitting
B = A' * A;
c = A' * scaled_y;
a = B \ c; % Polynomial coefficients
% Create Vandermonde matrix for evaluation
Aplot = ones(length(xplot), m+1);
for j = 2:m+1
Aplot(:, j) = xplot.^(j-1);
end
% Evaluate the polynomial
yFit = Aplot * a;
% Plot the data and the polynomial
figure;
plot(scaled_x, scaled_y, '*'
, xplot, yFit, '-'
);
xlabel(
'x'
);
ylabel(
'y'
);
title([
'Polynomial Fit with m = '
, num2str(m)]);
grid on
;
legend(
'true values'
,
'best fit line'
)
NKK
end
The code block above performs polynomial fitting using the Vandermonde matrix and
least squares method for different polynomial degrees (5, 10, 15, 20, and 25) on a set of 82 data
points that have been scaled to the range [-1, 1]. For each specified degree, the code constructs a Vandermonde matrix based on the scaled
x-values, solves the least squares problem to determine the polynomial coefficients, and then
evaluates these polynomials at 1001 evenly spaced points within [-1, 1]. Each resulting
polynomial is plotted against the scaled data, allowing for visual comparison of the fit quality
across different polynomial degrees. This procedure illustrates how increasing the polynomial degree affects the fit to the data,
highlighting the trade-off between fitting the data closely and potentially overfitting, especially
with higher degrees.
The graphs obtained for each degree of polynomial regression are as follow:
6
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
(The graphs will be appeared in the next page)
Figure 2.1:
A graph plotting the same data using Vandermore Regression at polynomial degree 5.
This fit appears to be quite smooth and possibly underfitting the data, as it does not capture all the variations in the dataset. This is expected with lower-degree polynomials, which have fewer coefficients and hence less flexibility to fit complex patterns.
7
Figure 2.2:
A graph plotting the same data using Vandermore Regression at polynomial degree 10.
The polynomial of degree 10 seems to fit the data better than m = 5, showing more flexibility and better adaptation to the curvature of the data points. It captures more of the data's structure without appearing to overfit.
8
Figure 2.3:
A graph plotting the same data using Vandermore Regression at polynomial degree 15.
The fit for m = 15 continues the trend of increasing conformity to the data points. The polynomial starts to indicate slight overfitting tendencies, as it begins to exhibit more fluctuations to reach individual data points.
9
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Figure 2.4:
A graph plotting the same data using Vandermore Regression at polynomial degree 20.
At this degree, the polynomial is fitting very closely to the data points. While the overall trend is followed, there is a visible indication that the polynomial might be capturing noise as well as the underlying data structure.
10
Figure 2.5:
A graph plotting the same data using Vandermore Regression at polynomial degree 25.
The polynomial of degree 25 shows clear signs of overfitting, particularly towards the ends of the range. The oscillations and deviations from the general trend at the extremities are typical signs of a polynomial that is too complex for the data, which can lead to poor predictive performance on new, unseen data.
11
Add the following code snippet in the for loop in part (c) before end of loop. From here, we can retrieve the least squared error E for each corresponding polynomial degree m
. yFit = A * a;
% Calculate the least squares error
E = sum((scaled_y - yFit).^2);
printf(
'Least Squares Error for m = %d: %f\n'
, m, E);
After running the above code, we are able to get the results as follows:
Least Squares Error for m = 5: 0.985991
Least Squares Error for m = 10: 0.125133
Least Squares Error for m = 15: 0.090016
Least Squares Error for m = 20: 0.082654
Warning: Matrix is close to singular or badly scaled. Results may be inaccurate. RCOND = 5.068625e-19. Least Squares Error for m = 25: 0.081382
The least squares errors for polynomial fits with degrees ranging from 5 to 25 show a
trend of decreasing error as the polynomial degree increases, suggesting tighter fits with higher
degrees. However, the marginal error reduction from a 20th to a 25th-degree polynomial,
alongside a warning of numerical instability indicated by a very small RCOND value, points to
the diminishing benefits and increasing risks of overfitting and numerical issues with higher-
degree polynomials. This implies that while higher degrees can offer marginally better fits, they
come with the cost of potential overfitting and unreliable results due to ill-conditioning of the
Vandermonde matrix. A polynomial degree between 10 and 15 seems to provide a reasonable
balance between fitting accuracy and numerical stability, avoiding the pitfalls of excessive
complexity.
12
(d)
(10 points)
In each of the five cases calculate the least squares error E
=
∑
i
=
1
82
(
y
i
−
p
(
x
i
)
)
2
where y
i
are the data values at points x
i
and p
(
x
i
)
are the calculated
values of the least squares polynomial. Compare the errors with the cases in which
MATLAB has problems with the equations as evidenced by a condition number error
message. Note that the distance between the least squares polynomial and the data may
not change all that much as the polynomial degree is varied from 5 to 25.
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
(End of Student’s answer for Problem 1)
13
Problem 2:
Truss Structure and Solving Matrix Equation (50 points)
14
15
In this problem,
you will build your own
bridge and see for yourself
why solving systems of
equations with accuracy
and precision is important.
You must build a bridge
using this tool
that looks
like any of the following:
Feel free to use your
imagination and creativity
to
build
interesting
structures. It is highly
recommended that you
play around with the tool
to get comfortable using it.
Think about where the
forces on the bridge could
be acting on. A quick
google search on trusses
and types of ‘supports’
and ‘forces’ used in
bridges will get you up to
speed on how to declare
them in the simulator. Feel
free to experiment and
create!
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
In this Problem, I am going to use the pre-built truss number 3 for calculation:
Figure 3.1:
Pre-built Truss Structure #3
16
Once you are done building your bridge, click on ‘Show matrix eqns’ and you should
be able to see all matrices which give you information about everything. It’s in the form Ax =
b. ‘A’ tells you about how members, supports, and nodes are connected in 2D space. ‘B’ tells
you the forces acting on nodes [+/- tell the directions], and the ‘x’ tells you the forces acting
on different members, supports, etc. When building real bridges, one can approximate A and
B to calculate ‘x’. It is very important that engineers know how much force each member and
support experiences so that an appropriate material in the required dimension is used. [In real
world, engineers use reasonably good approximations to account for all conditions while
declaring both A and b, however realworld conditions can be very hard to quantify
accurately.] Now, copy matrix A and b. Assume that you do not know ‘x’. Implement a MATLAB
program to compute ‘x’ using any technique of your choice in MATLAB. Write a detailed
explanation using the ideas explored in the question to explain your results here and
uncertainties that could be involved in them. Please include your constructed bridge pictures
in the report as well. Speculate and write about the number of equations that one would have
to solve while building a real-world bridge, and the challenges involved in.
[Note: if you don’t feel comfortable using the tool and creating your own structure,
select pre-built truss number ‘3’ and solve for it.]
Using the pre-built truss, I am able to import a .xls spreadsheet containing two
spreadsheets with matrix A and b respectively, both are in the matrix_data.xls
.
For the coding part, I was using the code snippet below:
% Read the input matrix
A = readmatrix(
'matrix_data.xls'
,
'Sheet'
,
'matrixA'
,
'Range'
,
'A1:R18'
);
b = readmatrix(
'matrix_data.xls'
,
'Sheet'
,
'matrixB'
,
'Range'
,
'A1:A18'
);
% Check if matrix A is square and invertible
if rank(A) == min(size(A))
% If A is square and full rank, we can solve the system directly
x = A\b;
else
% If A is not square or not full rank, we need to use a least squares solution
x = pinv(A)*b;
end
% Output the result
disp(x);
The code snippet solves the linear system Ax = b by first reading matrices A and b from
an Excel file using the readmatrix function. It then checks if A is a square and full-rank matrix,
which indicates that a unique solution can be found. If A is square and full-rank, the code uses
MATLAB's backslash operator \ to solve the system directly, which is an efficient method that
leverages matrix factorization techniques. If A is not square or not full-rank, indicating the
system is underdetermined or overdetermined, the code computes the pseudoinverse of A with
pinv(A) and finds a least squares solution, which minimizes the residuals between the actual and
predicted values. The solution x is then displayed using disp(x), providing either the exact or an
approximate solution to the system of equations defined by the matrices from the Excel file.
In computational mathematics, the precision of numerical calculations is finite, leading to
rounding errors. This is a consequence of the finite representation of numbers in computer
memory and the operations performed on them. When solving systems of linear equations, as in
the case of bridge force analysis, these rounding errors can accumulate, resulting in small
discrepancies between expected and actual results. In engineering practice, a slight deviation in
the magnitude of computed forces is typically acceptable, as designs incorporate safety factors to
account for such uncertainties.
The accuracy of solutions to linear systems also depends on the condition number of the
matrix A. A matrix with a high condition number is considered ill-conditioned, meaning that
17
small changes in the matrix or the vector b can cause large changes in the solution x. In
engineering computations, it is essential to check the condition number to assess the stability and
reliability of the solution, especially when the system is sensitive to perturbations.
Engineering models, by necessity, simplify the complex behaviors of real-world
structures into manageable calculations. These simplifications can include assuming linear
material properties, idealized connections, and static loading conditions. Such assumptions are
standard in preliminary design stages but can diverge from actual conditions. Real structures may
behave non-linearly, have varying material properties, and be subjected to dynamic loads that are
not captured in simplified static models.
Material properties used in calculations are typically derived from standardized tests and
may not precisely reflect the properties of the materials used in construction, which can exhibit
variability. The strength, stiffness, and durability of construction materials can differ due to
factors like manufacturing inconsistencies, treatment variations, and the impact of environmental
conditions. Engineers must consider these variations to ensure that structures can withstand
unforeseen stresses over their service life.
The loads applied to a bridge in a model, represented by vector b, are estimates based on
anticipated usage scenarios. However, actual loads can vary significantly due to factors such as
traffic volume, vehicle weights, and environmental conditions. These uncertainties can be
mitigated by applying conservative load estimates and incorporating dynamic load analysis to
better approximate the range of conditions the bridge will experience.
When scaling up from a model to a real-world bridge, the number of equations increases
dramatically due to the addition of more members, supports, and load cases. A real bridge is a
three-dimensional structure with complex load paths, and its analysis may involve solving a large
system of simultaneous equations that capture the interactions between all elements of the bridge
under various loading conditions.
Finally, the real-world calculation of forces in bridge structures faces numerous
challenges beyond the scale and complexity of the equations. These include accounting for non-
18
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
linear behavior under extreme loads, time-dependent effects such as creep and shrinkage, and the
impact of dynamic and transient forces like wind, earthquakes, and vehicular traffic. Moreover,
long-term effects such as corrosion, fatigue, and wear must be factored into the design to ensure
durability and safety throughout the bridge's operational lifespan. Advanced modeling techniques
such as finite element analysis are employed to address these challenges, coupled with empirical
data and safety factors to ensure a robust design.
(End of Student’s answer for Problem 2)
19
REFERENCES
1.
MATLAB code for reading and processing data from a text file:
a.
MathWorks. (n.d.). fopen [Function documentation]. MATLAB Documentation. Retrieved from https://www.mathworks.com/help/matlab/ref/fopen.html
b.
MathWorks. (n.d.). feof [Function documentation]. MATLAB Documentation. Retrieved from https://www.mathworks.com/help/matlab/ref/feof.html
c.
MathWorks. (n.d.). fgetl [Function documentation]. MATLAB Documentation. Retrieved from https://www.mathworks.com/help/matlab/ref/fgetl.html
d.
MathWorks. (n.d.). sscanf [Function documentation]. MATLAB Documentation. Retrieved from https://www.mathworks.com/help/matlab/ref/sscanf.html
e.
MathWorks. (n.d.). fclose [Function documentation]. MATLAB Documentation. Retrieved from https://www.mathworks.com/help/matlab/ref/fclose.html
2.
MATLAB code for plotting, scaling, and polynomial fitting:
a.
MathWorks. (n.d.). plot [Function documentation]. MATLAB Documentation. Retrieved from https://www.mathworks.com/help/matlab/ref/plot.html
b.
MathWorks. (n.d.). linspace [Function documentation]. MATLAB Documentation. Retrieved from https://www.mathworks.com/help/matlab/ref/linspace.html
c.
MathWorks. (n.d.). legend [Function documentation]. MATLAB Documentation. Retrieved from https://www.mathworks.com/help/matlab/ref/legend.html
3.
MATLAB code for matrix operations and solving systems of equations:
a.
MathWorks. (n.d.). readmatrix [Function documentation]. MATLAB Documentation. Retrieved from https://www.mathworks.com/help/matlab/ref/readmatrix.html
b.
MathWorks. (n.d.). rank [Function documentation]. MATLAB Documentation. Retrieved from https://www.mathworks.com/help/matlab/ref/rank.html
c.
MathWorks. (n.d.). pinv [Function documentation]. MATLAB Documentation. Retrieved from https://www.mathworks.com/help/matlab/ref/pinv.html
20
Related Documents
Recommended textbooks for you
Programming Logic & Design Comprehensive
Computer Science
ISBN:9781337669405
Author:FARRELL
Publisher:Cengage

EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT

Microsoft Visual C#
Computer Science
ISBN:9781337102100
Author:Joyce, Farrell.
Publisher:Cengage Learning,

Programming with Microsoft Visual Basic 2017
Computer Science
ISBN:9781337102124
Author:Diane Zak
Publisher:Cengage Learning

C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning
COMPREHENSIVE MICROSOFT OFFICE 365 EXCE
Computer Science
ISBN:9780357392676
Author:FREUND, Steven
Publisher:CENGAGE L
Recommended textbooks for you
- Programming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:CengageEBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENTMicrosoft Visual C#Computer ScienceISBN:9781337102100Author:Joyce, Farrell.Publisher:Cengage Learning,
- Programming with Microsoft Visual Basic 2017Computer ScienceISBN:9781337102124Author:Diane ZakPublisher:Cengage LearningC++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage LearningCOMPREHENSIVE MICROSOFT OFFICE 365 EXCEComputer ScienceISBN:9780357392676Author:FREUND, StevenPublisher:CENGAGE L
Programming Logic & Design Comprehensive
Computer Science
ISBN:9781337669405
Author:FARRELL
Publisher:Cengage

EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT

Microsoft Visual C#
Computer Science
ISBN:9781337102100
Author:Joyce, Farrell.
Publisher:Cengage Learning,

Programming with Microsoft Visual Basic 2017
Computer Science
ISBN:9781337102124
Author:Diane Zak
Publisher:Cengage Learning

C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning
COMPREHENSIVE MICROSOFT OFFICE 365 EXCE
Computer Science
ISBN:9780357392676
Author:FREUND, Steven
Publisher:CENGAGE L