Is my coding assignment correct?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi all, I've been working on this assignment for a few hours & searching for the right way to code this but I'm still unsure if it is correct. Can someone please let me know if this is correct. I'm mostly unsure about 4 and 5.
Instructions.
1. [1 pt] Generate this set of linear data:
x0 = 1:1:20;
y0 = -5 +2*x0;
2a. [1 pt] Add measurement to the y values:
y1 = y0 + 1.0*randn(size(y0));
2b. (1 pt) Open a new figure and plot the noisy data with black circle markers:
3. [3 pts] Use polyfit( ) to fit a line to the noisy data.
4. [3 pts] Use polyval( ) to compute the y-values of the fitted line, using x0 for the x-values.
5. [1 pt] Plot the fitted line on the same figure as the noisy data. Use a red dashed line: 'r--'
My code.
x0 = 1:1:20;
y0 = -5 +2*x0;
y1 = y0 + 1.0*randn(size(y0));
figure;
plot(x0,y1,'o','MarkerFaceColor','k')
grid on;
hold on;
coeffs2 = polyfit(x0,y1,1);
besty = coeffs2(1)*x0 + coeffs2(2);
plot(x0,y1,'o',x0,besty)
x2 = linspace(0,2);
y2 = polyval(coeffs2,x2)
plot(x2,y2,'r--')
1 Kommentar
Dyuman Joshi
am 30 Nov. 2022
It looks good, but there's a bit of redundant code
%Task 1
x0 = 1:1:20;
y0 = -5 +2*x0;
%Task 2a
y1 = y0 + 1.0*randn(size(y0));
%Task 2b
figure;
plot(x0,y1,'k.','MarkerSize',10)
grid on;
hold on;
%Task 3
coeffs2 = polyfit(x0,y1,1);
%Task 4
y2 = polyval(coeffs2,x0);
%Task 5
plot(x0,y2,'r--')
Antworten (0)
Siehe auch
Kategorien
Mehr zu Line Plots finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!