r squared comparing sine waves

40 visualizaciones (últimos 30 días)
C.G.
C.G. el 18 de Mayo de 2022
Respondida: Rishav el 11 de Oct. de 2023
I have a dataset to which I have asked matlab to fit a sine wave. I want to find the r^2 value to see how well the sine curve I have generated fits the data.
Is there a simple way of doing this?
x1 = time';
y = Qe_mean;
yu = max(y);
yl = min(y);
yr = (yu-yl);
yz = y-yu+(yr/2);
zx = time(yz .* circshift(yz,[0 1]) <= 0);
P = period;
ym = mean(Qe_mean);
fit = @(b,x) b(1).*(sin(2*pi*x./P + 2*pi/b(2))) + b(3);
fcn = @(b) sum((fit(b,x1) - y).^2);
s = fminsearch(fcn, [yr; -1; ym])
xp = linspace(min(x1),max(x1),P);
figure()
plot(xp,fit(s,xp), 'b')
hold on
plot(time,y,'k','Linewidth',1)

Respuestas (1)

Rishav
Rishav el 11 de Oct. de 2023
Hi C.G.,
I understand that you want to find the r^2 value to see how well the generated sine curve fits the data.
To calculate the coefficient of determination (R-squared) for your sine wave fit in MATLAB, you can use the following steps. You can use the corrcoef function to calculate the correlation between your observed data and the fitted sine wave. Here's how you can do it:
Calculate the R-squared value:
% Calculate the fitted sine wave
fitted_sine_wave = fit(s, x1);
% Calculate the correlation coefficient
corr_matrix = corrcoef(y, fitted_sine_wave);
% Extract the R-squared value
r_squared = corr_matrix(1, 2)^2;
disp(['R-squared value: ', num2str(r_squared)]);
The corrcoef function calculates the correlation matrix between two datasets, and corr_matrix(1, 2) gives you the correlation coefficient between your observed data (y) and the fitted sine wave (fitted_sine_wave). The R-squared value is simply the square of this correlation coefficient.
Here's the modified code with the R-squared value calculation included:
x1 = time';
y = Qe_mean;
yu = max(y);
yl = min(y);
yr = (yu - yl);
yz = y - yu + (yr / 2);
zx = time(yz .* circshift(yz, [0 1]) <= 0);
P = period;
ym = mean(Qe_mean);
fit = @(b, x) b(1) * (sin(2 * pi * x ./ P + 2 * pi / b(2))) + b(3);
fcn = @(b) sum((fit(b, x1) - y).^2);
s = fminsearch(fcn, [yr; -1; ym]);
xp = linspace(min(x1), max(x1), P);
figure();
plot(xp, fit(s, xp), 'b');
hold on;
plot(time, y, 'k', 'Linewidth', 1);
% Calculate the R-squared value
fitted_sine_wave = fit(s, x1);
corr_matrix = corrcoef(y, fitted_sine_wave);
r_squared = corr_matrix(1, 2)^2;
disp(['R-squared value: ', num2str(r_squared)]);
The R-squared value indicates how well the sine wave fits your data, with a value of 1 indicating a perfect fit and lower values indicating a less perfect fit.
Thank you,
Rishav Saha

Categorías

Más información sobre Statistics and Machine Learning Toolbox en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by