how can i plot adjusted r squared and sum of squared error separately in matlab

To plot the adjusted R-squared and sum of squared error separately in MATLAB, you would need to calculate these values first. Here is an example of how you can do it:

main.m
% Sample data
x = [1, 2, 3, 4, 5];
y = [2, 4, 6, 8, 10];

% Linear regression
p = polyfit(x, y, 1);
y_pred = polyval(p, x); % Predicted y values

% Residuals
residuals = y - y_pred;

% Mean squared error (MSE)
mse = mean(residuals.^2);

% Total sum of squares (TSS)
tss = sum((y - mean(y)).^2);

% R-squared
rsquared = 1 - (sum(residuals.^2) / tss);

% Adjusted R-squared
n = length(y);
p = 1; % Number of predictors
adj_rsquared = 1 - ((1 - rsquared) * (n - 1) / (n - p - 1));

% Plotting
figure;

subplot(2,1,1);
scatter(x, y);
hold on;
plot(x, y_pred, 'r');
xlabel('x');
ylabel('y');
legend('Data', 'Linear fit');
title('Linear Regression');

subplot(2,1,2);
bar(1, mse);
hold on;
bar(2, adj_rsquared);
xticks([1, 2]);
xticklabels({'MSE', 'Adjusted R-squared'});
ylabel('Value');
title('Performance Metrics');

814 chars
47 lines

In this code, we first define the sample data x and y. Then we perform a linear regression using the polyfit function to obtain the coefficient values. The predicted y values are calculated using polyval.

Next, we calculate the residuals by subtracting the predicted y values from the actual y values. The mean squared error (MSE) is computed by taking the mean of squared residuals.

We also calculate the total sum of squares (TSS) to obtain the R-squared value, which is given by 1 minus the ratio of the sum of squared residuals to TSS.

Finally, we calculate the adjusted R-squared using the formula which takes into account the number of observations n and the number of predictors p.

The results are then plotted using the scatter, plot, and bar functions in MATLAB.

Note: This example assumes a simple linear regression with only one predictor variable (x), but the code can be adapted for more complex models.

related categories

gistlibby LogSnag