Error using .* Matrix dimensions must agree.

I worked on a machine at my Uni and wrote a code. It had a very long equation, consists of plenty of single value variables, except for 2. One was 1x15,000, the other was 2x1. The code worked perfectly providing me a 2x15,000 array as predicted. Then I went home and tried the code on my machine, ran the code (without any changes) and got the: "Error using .* Matrix dimensions must agree.".
So I decided to check the problem on a much simpler calculation, so I entered:
x=[1 2];
y=[3;4];
z=x.*y
I got the same error again:
Error using .*
Matrix dimensions must agree.
Error in Test (line 3)
z=x.*y
Clearly, the result I should've gotten is this:
z =
3 6
4 8
So I suspect something is off with my MATLAB version. Maybe something in my MATLAB's preferences could be causing this to fail?

 採用された回答

Star Strider
Star Strider 2017 年 12 月 27 日

2 投票

You may have to use the bsxfun (link) function to make it work on both machines without encountering compatibility problems. In R2016b (if I remember correctly) ‘implicit expansion’ became the default, so operations that previously required bsxfun would then work without it. So I suspect your machine is running R2016a or earlier, and the uni machine is running R2016b or later.
This bsxfun call:
x=[1 2];
y=[3;4];
z = bsxfun(@times, x, y)
z =
3 6
4 8
will give you the result you expect.

3 件のコメント

Star Strider
Star Strider 2017 年 12 月 27 日
Alo Gr’s “Answer” moved here:
Yep, It makes a lot of sense, my uni has a 2017 while I have a 2015 version. The expression I'm using is very long and complicated, so using the bsxfun you suggested would be very difficult to use. Is there a way maybe to enable 'implicit expansion' in older versions?
Thanks for your prompt response.
Star Strider
Star Strider 2017 年 12 月 27 日
My pleasure.
‘Is there a way maybe to enable 'implicit expansion' in older versions?’
Not ot my knowledge. You need to go through each such multiplication and replace it with a bsxfun call. You can write an anonymous function that would make that a bit easier.
Most MATLAB changes are enhancements. This one causes significant backward-compatibility problems. That is the reason I continue to use bsxfun in my Answers, even when the Question specifically mentions versions R2016b or later.
You have my most profound sympathies. Unfortunately, that is the best that either — or MathWorks — can do to solve your problem.
Matt J
Matt J 2017 年 12 月 27 日
Thanks for your prompt response.
@Alo Gr, If Star Strider's answer has solved your issue, you should "Accept" click it.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeMATLAB についてさらに検索

製品

質問済み:

2017 年 12 月 27 日

コメント済み:

2017 年 12 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by