How to resolve Matrix dimensions error?
Show older comments
Hi, May I know how to resolve this error? Thank You!
Error part Matrix dimensions must agree.
Error in MathCW (line 15) v = [ones(21,1) I2 I2.^2].\PN0;
Accepted Answer
More Answers (3)
AVB
on 10 Dec 2020
Next time please make sure you copy the code block in your question using the 'Insert a line of code' option.
There were two issues.
- The matrix [ones(21,1) I2 I2.^2] is of 21x3 size hence PNO should have compatible size which means it should be of size 21x1
- The first argument in the polyval function should be polynomial coefficients (in descending powers) of an nth-degree polynomial. See polyval
Below is your updated code:
% Increment of current
I=0:0.5:(0.5*20);
I2=transpose(I);
% Power measurements
Po=I.*I*100;
for experiment = 1:10
% Noise with sd 0
noise0=randn(1,21);
PN0=Po+(0.*noise0);
scatter(I,Po);
hold on
scatter(I,PN0,'filled');
hold off
x = polyfit(I,PN0,2);
v = [ones(21,1) I2 I2.^2].\PN0';
y = polyval(x,I);
% Error
E =(Po-y).^2;
Em=mean(E);
end
Paul Hoffrichter
on 10 Dec 2020
E =(Po-y).^2; % ( 1x21 - 1x3 ) .^ 2
is this what you want:
E =(Po-y').^2; % ( 1x21 -3x1 ) .^ 2
3 Comments
gp
on 10 Dec 2020
gp
on 10 Dec 2020
Paul Hoffrichter
on 10 Dec 2020
Edited: Paul Hoffrichter
on 10 Dec 2020
Yes. However, I have already fixed a core problem, so now the dimensions are the same. But the above dimensions are interesting. I am pretty sure this would not have worked 10 years ago. Here is a simple example to illustrate some newer matrix/vector operations.
>> t % 1x4
t =
10 20 30 40
>> u % 7x1
u =
0
2
4
6
8
9
10
>> t - u
ans =
10 20 30 40
8 18 28 38
6 16 26 36
4 14 24 34
2 12 22 32
1 11 21 31
0 10 20 30
If u was also a row vector, then its dimensions would have to equal t's dimensions. For example:
s = % 4x1
5 5 5 5
>> t - s
ans =
5 15 25 35
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!