# I keep getting an error on my correlation coefficient on line 20

조회 수: 12 (최근 30일)
Patrick 2024년 3월 15일
댓글: Chunru 2024년 3월 15일
% Given data
x = [0, 2, 4, 6, 9, 11, 12, 15, 17, 19];
y = [5, 6, 7, 6, 9, 8, 8, 10, 12, 12];
% Least-squares regression for a straight line
A = [x', ones(size(x'))];
b = y';
coefficients = A\b; % Compute the slope and intercept
slope = coefficients(1);
intercept = coefficients(2);
% Calculate the fitted values
y_fit = slope * x + intercept;
% Calculate the standard error of the estimate
error = y - y_fit;
standard_error = sqrt(sum(error.^2) / (length(x) - 2));
% Calculate the correlation coefficient
correlation_coefficient = corr(x', y');
% Plot the data and regression line
scatter(x, y, 'o', 'filled');
hold on;
plot(x, y_fit, 'r', 'LineWidth', 2);
hold off;
xlabel('x');
ylabel('y');
title('Least-Squares Regression: Straight Line');
legend('Data', 'Regression Line');

댓글을 달려면 로그인하십시오.

### 채택된 답변

Chunru 2024년 3월 15일
There is no error running here(see below). Can you show your error message?
% Given data
x = [0, 2, 4, 6, 9, 11, 12, 15, 17, 19];
y = [5, 6, 7, 6, 9, 8, 8, 10, 12, 12];
% Least-squares regression for a straight line
A = [x', ones(size(x'))];
b = y';
coefficients = A\b; % Compute the slope and intercept
slope = coefficients(1);
intercept = coefficients(2);
% Calculate the fitted values
y_fit = slope * x + intercept;
% Calculate the standard error of the estimate
error = y - y_fit;
standard_error = sqrt(sum(error.^2) / (length(x) - 2));
% Calculate the correlation coefficient
correlation_coefficient = corr(x', y');
% Plot the data and regression line
scatter(x, y, 'o', 'filled');
hold on;
plot(x, y_fit, 'r', 'LineWidth', 2);
hold off;
xlabel('x');
ylabel('y');
title('Least-Squares Regression: Straight Line');
legend('Data', 'Regression Line', "location", "northwest");
##### 댓글 수: 2없음 표시없음 숨기기
Patrick 2024년 3월 15일
편집: Patrick 2024년 3월 15일
Error in Patrick_B_Homework8_9_2 (line 20)
correlation_coefficient = corr(x', y');
This is the error message
Chunru 2024년 3월 15일
Try the following:
• do "clear" before running your program
• which corr
• run "dbstop error" before running your program

댓글을 달려면 로그인하십시오.

### 카테고리

Help CenterFile Exchange에서 Linear and Nonlinear Regression에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!

Translated by