开发者

MATLAB: not calculating correctly...user error?

I have been looking at this code for a while now, and cannot figure out why matlab is not calculating correctly. Does anyone see anything that I may be doing wrong with this code?

((1-EU_P2par3(:,1))*US_P2par3(:,1))+((1-EU_P2par3(:,2))*US_P2par3(:,2))+((开发者_Go百科1-EU_P2par3(:,3))*US_P2par3(:,3))+((1-EU_P2par3(:,4))*US_P2par3(:,4))+((1-EU_P2par3(:,5))*US_P2par3(:,5))+((1-EU_P2par3(:,6)*US_P2par3(:,6)))+((1-EU_P2par3(:,7))*US_P2par3(:,7))

Thanks for all the help!


In cases like this, good code formatting is your friend. Using an ellipsis (i.e. ..., the line continuation symbol) to create a multi-line statement can help greatly...

It looks like you have a parenthesis in the wrong place. Your code looks like this:

result = ((1-EU_P2par3(:,1))*US_P2par3(:,1))+...
         ((1-EU_P2par3(:,2))*US_P2par3(:,2))+...
         ((1-EU_P2par3(:,3))*US_P2par3(:,3))+...
         ((1-EU_P2par3(:,4))*US_P2par3(:,4))+...
         ((1-EU_P2par3(:,5))*US_P2par3(:,5))+...
         ((1-EU_P2par3(:,6)*US_P2par3(:,6)))+...  %# Notice something here?
         ((1-EU_P2par3(:,7))*US_P2par3(:,7));

And you probably want this:

result = ((1-EU_P2par3(:,1))*US_P2par3(:,1))+...
         ((1-EU_P2par3(:,2))*US_P2par3(:,2))+...
         ((1-EU_P2par3(:,3))*US_P2par3(:,3))+...
         ((1-EU_P2par3(:,4))*US_P2par3(:,4))+...
         ((1-EU_P2par3(:,5))*US_P2par3(:,5))+...
         ((1-EU_P2par3(:,6))*US_P2par3(:,6))+...  %# Notice the change?
         ((1-EU_P2par3(:,7))*US_P2par3(:,7));

EDIT:

In addition, as Darren mentions in his answer, you will likely have to use the element-wise multiplication operator .* instead of the matrix multiplication operator *. Explanations of the arithmetic operators can be found here.

Also, your calculation can be greatly simplified by vectorizing it using the function SUM, like so:

result = sum((1-EU_P2par3(:,1:7)).*US_P2par3(:,1:7),2);


Try the following example.

xy = rand(10,2);

a = xy(:,1)*xy(:,2); % ??? Error using ==> mtimes % Inner matrix dimensions must agree.

a = xy(:,1).*xy(:,2);

The error arises when you attempt to multiply vectors together. You must use the .* operator to get element-wise multiplication

Hope that helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜