Clear Filters
Clear Filters

incorrect dimensions in data set

1 view (last 30 days)
Kathleen
Kathleen on 30 Sep 2023
Edited: Torsten on 30 Sep 2023
Hi,
I keep running into an error for incorrect dimensions and not sure on how to fix it.
%% Generate the data set
m_true = [10; 100; 9.8];
sigma = 8;
t = linspace(0, 10, 10);
y = m_true(1) + m_true(2)*t - m_true(3)*t^2/2 + sigma*randn(10, 1);
% Construct the G matrix
G = [ones(10, 1), t, -(1/2)*t.^2];
% Solve for the least squares parameters
m_L2 = (G'*G)\G'*y;
% Calculate the model covariance matrix
cov_m_L2 = (G'*G)\sigma^2;
% Calculate the 95% confidence intervals for the model parameters
alpha = 0.05;
t_crit = tinv(1 - alpha/2, 10 - 3);
chi_m_L2 = m_L2 +- t_crit * sqrt(diag(cov_m_L2));
% Calculate the p-value for the regression
chi2_stat = sum((y - G*m_L2).^2 / sigma^2);
p_value = chi2cdf(chi2_stat, 10 - 3);
% Display the results
fprintf('Model parameters: %f %f %f\n', m_L2);
fprintf('Confidence intervals: [%f %f] [%f %f] [%f %f]\n', ci_m_L2(1, :));
fprintf('p-value: %f\n', p_value);

Accepted Answer

Torsten
Torsten on 30 Sep 2023
Edited: Torsten on 30 Sep 2023
The code works technically. But after all the changes I made, it's not clear if it does what you want.
This line needs correction:
chi_m_L2 = m_L2 +- t_crit * sqrt(diag(cov_m_L2));
You won't make chi_m_L2 a two-element vector this way.
%% Generate the data set
m_true = [10; 100; 9.8];
sigma = 8;
t = linspace(0, 10, 10).';
y = m_true(1) + m_true(2)*t - m_true(3)*t.^2/2 + sigma*randn(10, 1);
% Construct the G matrix
G = [ones(10,1), t, -(1/2)*t.^2];
% Solve for the least squares parameters
m_L2 = (G'*G)\(G'*y);
% Calculate the model covariance matrix
cov_m_L2 = (G'*G)/sigma^2;
% Calculate the 95% confidence intervals for the model parameters
alpha = 0.05;
t_crit = tinv(1 - alpha/2, 10 - 3);
chi_m_L2 = m_L2 +- t_crit * sqrt(diag(cov_m_L2));
% Calculate the p-value for the regression
chi2_stat = sum((y - G*m_L2).^2 / sigma^2);
p_value = chi2cdf(chi2_stat, 10 - 3);
% Display the results
fprintf('Model parameters: %f %f %f\n', m_L2);
Model parameters: 17.667507 98.298688 9.589608
fprintf('Confidence intervals: [%f %f] [%f %f] [%f %f]\n', chi_m_L2(1, :));
Confidence intervals: [16.732807
fprintf('p-value: %f\n', p_value);
p-value: 0.824519

More Answers (0)

Categories

Find more on Statistics and Machine Learning Toolbox in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!