Cost.m Function

1 次查看(过去 30 天)
Joe Deyak
Joe Deyak 2021-3-23
Im doing this problem in class and it keeps telling me I have an error. Please help.
function [ J ] = cost( z )
a = z(1);
b = z(2);
c = z(3);
d = z(4);
e = z(5);
f = z(6);
w = [0:0.1:10]';
s = j*w;
Gideal = 1 * (w < 6);
G = a ./ ((s + b) *(s.^2 + c*s + d) *(s.^2 + e*s + f));
e = abs(Gideal) - abs(G);
J = sum(e .^ 2);
plot(w,abs(Gideal),w,abs(G));
pause(0.01);
end
  1 个评论
Geoff Hayes
Geoff Hayes 2021-3-23
Joe - please copy and paste the full error message to this question. Is it something similar to
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix
matches the number of rows in the second matrix.
or something else?

请先登录,再进行评论。

回答(1 个)

Vashist Hegde
Vashist Hegde 2021-3-26
DISCLAIMER: These are my own views and in no way depict those of MathWorks.
Hello Joe,
The error you seem to be gettting is:
Error using *
Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To perform elementwise
multiplication, use '.*'.
This is because in the line:
G = a ./ ((s + b) *(s.^2 + c*s + d) *(s.^2 + e*s + f));
you have used '*' operator to multiply the terms in the denominator. But in MATLAB '*' operator is considered to be matrix multiplication by default. And if we check the dimensions of each term you are trying tu multiply, this is the result:
Which are clearly incompatible for matrix multiplication.
Since you are trying to carry out element-wise multiplication, the right operator would be '.*'
hence the right expression would be:
G = a ./ ((s + b) .*(s.^2 + c*s + d) .*(s.^2 + e*s + f));
Hope this helps.

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by