"Matrix dimensions must agree" despite using .*

1 view (last 30 days)
Ivan Zackazow
Ivan Zackazow on 20 Apr 2017
Answered: Star Strider on 20 Apr 2017
Matrix dimensions must agree.
Error in nnCostFunction (line 74) delta1_h = (d2).*(X1_tr);
d2 and X1_tr are the two vectors wich have sizes unsuitable for matrix multiplication, but my goal is element-wise multiplication and somehow Matlab fails to do it. Can you please help me with this problem?
In the console I've tried element-wise multiplication of [1 2 3] and [2; 3; 4; 5]. It was alright. Wonder what may be wrong here.
Thank you.

Answers (1)

Star Strider
Star Strider on 20 Apr 2017
It’s called ‘implicit expansion’ and is new in R2016b.
The ‘traditional’ (and my preferred) way to do this is to use the bsxfun function to achieve the same result:
a = [1 2 3];
b = [2; 3; 4; 5];
q1 = bsxfun(@times, a, b);
q2 = bsxfun(@times, b, a);
You will get the same result regardless of the way the operators are entered.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!