Why is operation between column and row vector so slow
Show older comments
For example, lets define two vectors:
>> a = rand(20000,1);
>> b = rand(1,20000);
Now element wise divide them:
>> tic;a./b;toc
Elapsed time is 0.267177 seconds.
>> tic;a./b';toc
Elapsed time is 0.053040 seconds.
Notice that if the size of two vectors are the same, it is almost 5 times faster. Is this a bug? I'm not expecting to see such huge speed difference. And if this is the case perhaps I should review all my previous code to optimize for such characteristic.
Update: I found this in the doc, potentially a bug in the implicit expansion procedure?
Compatibility Considerations
Implicit expansion change affects arguments for operators
Behavior changed in R2016b
Starting in R2016b with the addition of implicit expansion, some combinations of arguments for basic operations that previously returned errors now produce results. For example, you previously could not add a row and a column vector, but those operands are now valid for addition. In other words, an expression like [1 2] + [1; 2] previously returned a size mismatch error, but now it executes.
If your code uses element-wise operators and relies on the errors that MATLAB previously returned for mismatched sizes, particularly within a try/catch block, then your code might no longer catch those errors.
For more information on the required input sizes for basic array operations, see Compatible Array Sizes for Basic Operations.
Update again: I just realize that the result is a square matrix. This is not a bug. Thanks guys!
3 Comments
Bruno Luong
on 24 Mar 2021
Why it's a BUG? It's documented there.
Stephen23
on 24 Mar 2021
"Notice that if the size of two vectors are the same, it is almost 5 times faster. Is this a bug?"
Have you compared the outputs? That will give you a clue why they require different times (hint: not a bug).
Ken Wang
on 24 Mar 2021
Accepted Answer
More Answers (0)
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!