Cost.m Function

1 回表示 (過去 30 日間)
Joe Deyak
Joe Deyak 2021 年 3 月 23 日
回答済み: Vashist Hegde 2021 年 3 月 26 日
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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by