error in Matlab function: Inner matrix dimensions must agree
显示 更早的评论
Hi, I wrote this function in Matlab:
function f = objfun(x,a,b)
x1 = x(1:24);
y1 = x(25:end);
i = 1:24;
if x(i)~=0
x(i+24)=0
end
if x(i+24)~=0
x(i)=0
end
f = -mean (x1*a')+mean(y1*b');
end
x1, y1, a and b are 1x24 vectors.
I get an error message that Inner matrix dimensions must agree! I don't know what is the problem, because when I write -mean (x1*a')+mean(y1*b') in the command window it gives me the correct answer, but when I run the code it gives error message about f. I also tried with .* but still I get the same error. Could you please help me to find the reason? Thanks!
回答(1 个)
Rik
2017-7-7
This function does very little. It is equivalent to this:
function f = objfun(x,a,b)
x1 = x(1:24);
y1 = x(25:end);
f = -(x1*a')+(y1*b');
end
You should really watch out with that last line. you're calculating the product, so following it up with mean is meaningless. I have assumed in my edit of your program that you meant an element-wise product.
You might mean the following function:
%generate random input (remove for your actual function)
x=round(rand(1,48));
a=rand(1,24);
b=rand(1,24);
x1 = x(1:24);
y1 = x(25:end);
%filter x1 and y1 (1 of them must be 0 for each position)
%the order of these two lines matters!!
x1(y1~=0)=0;
y1(x1~=0)=0;
f = -mean(x1.*a)+mean(y1.*b);
2 个评论
Sara
2017-7-7
Rik
2017-7-7
Of course for your function they are not random, but to test this code, I needed input.
Here you see the importance of a well worded question. Do you need that filtering step, and if so, is this what you meant? As for that E, you really need to think how you would solve this on paper. What are x1 and y1? What are a and b? Do you need an element-wise product? What do you actually need to do mathematically.
If you don't know what your code should do, it is impossible to write good code for it.
Another hint: use comments. Try to explain for each line of code what it does and what you need to accomplish. This will make debugging much easier, as you're forced to think about each line. (and it helps others and future you understand and debug your code)
类别
在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!