Hi, i have this error when running my regression programme: Error using - Matrix dimensions must agree. Error in mpg_regression (line 55) X21 = X11-mean(X11); My arrays are all 1x82 (i checked using disp(size())). Any help would be appreciated.

15 views (last 30 days)
mpg = importdata('carmpgdat.txt', '\t', 1);
VOL = mpg.data(:, 1);
HP = mpg.data(:, 2);
MPG = mpg.data(:, 3);
SP = mpg.data(:, 4);
WT = mpg.data(:, 5);
GPM = 1./MPG;
disp(size(VOL));
disp(size(HP));
disp(size(SP));
disp(size(WT));
X11 = [VOL HP SP WT];
mdl = fitlm(X11,MPG);
r2_1 = mdl.squared.Ordinary;
r2adj_1 = mdl.Rsquared.Adjusted;
p1 = 4;
X21 = X11-mean(X11);
X31 = X21/std(X21);
KS_1 = kstest2(X31, MPG);
  1 Comment
Greg
Greg on 24 Dec 2016
Except the only array in question is absolutely NOT 1x82. X11 = [VOL HP SP WT]; makes X11 either 1x328 or 4x82 (and as I look at your other code, I'm pretty sure it's actually 82x1 making X11 82x4). You are likely trying to subtract a 1x4 from an 82x4. In R2016b with implicit expansion, this should result in a successful subtraction. Prior to R2016b, this won't work.

Sign in to comment.

Accepted Answer

Greg
Greg on 24 Dec 2016
Edited: Greg on 24 Dec 2016
Assuming the clarifications in my comment on the question are confirmed, there are a few quick answers.
1) Run your code in R2016b (or future release).
2) Use repmat on mean(X11) to expand it to 82x4.
3) Use bsxfun. The first example in "help bsxfun" is exactly what you're trying to do.
Good luck.
  2 Comments
Jonny Little
Jonny Little on 24 Dec 2016
thank you Greg! I'm running on 2016a will update asap. One question though, will bsxfun still work on 2016b?
Greg
Greg on 28 Dec 2016
Edited: Greg on 28 Dec 2016
As far as I know, bsxfun hasn't changed moving to R2016b. The change is that in many situations you simply don't need to call it anymore. Further, the automatic implicit expansion has better performance than calling bsxfun (yay faster code!).
Quote from R2016b Release Notes: "Previously, this functionality was available via the bsxfun function. It is now recommended that you replace most uses of bsxfun with direct calls to the functions and operators that support implicit expansion. Compared to using bsxfun, implicit expansion offers faster speed of execution, better memory usage, and improved readability of code."
https://www.mathworks.com/help/matlab/release-notes.html?rntext=&startrelease=R2014a&endrelease=R2016b&category=Mathematics&groupby=release&sortby=descending&searchHighlight=

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!