Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Why does the following operation not throw an error?

1 回表示 (過去 30 日間)
Manuel
Manuel 2017 年 11 月 11 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
u =
0 0.7071 0.7071
0.7071 0 0.7071
0.7071 0.7071 0
>> u(i,:)
ans =
0 0.7071 0.7071
>> u2_mod I feel like the following is a source of error, because it could produce a behavior that is not wanted, but does not throw an error.
u2_mod =
0
0.6927
0.6927
>> u(i,:) - u2_mod
ans =
0 0.7071 0.7071
-0.6927 0.0144 0.0144
-0.6927 0.0144 0.0144
  1 件のコメント
Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan 2017 年 11 月 11 日
This is the documented behaviour of the '-' operator (see help minus). It will give you an output even if lengths along the Nth dimension do not match, as long as one of the operands is a scalar in that dimension.

回答 (2 件)

Veda Upadhye
Veda Upadhye 2017 年 11 月 14 日
Hi Manuel,
The output you get is the expected output as explained by Kaushik. Both the matrices are of compatible sizes: https://www.mathworks.com/help/matlab/matlab_prog/compatible-array-sizes-for-basic-operations.html
Here, the second operand in this operation would get scaled according to the size of the first operand.
Hope this helped!
-Veda

Manuel
Manuel 2017 年 11 月 16 日
In my opinion this operation should at least show a warning message, since one does not always check for the right indices (row or colum vector) and it could completely mess up the code.
  2 件のコメント
Guillaume
Guillaume 2017 年 11 月 16 日
since one does not always check for the right indices (row or colum vector)
One should always validate the assumptions that he makes when he writes code. In particular, if one writes code that expects a vector to be in a particular direction (e.g. a column vector), the first line of the code should be:
validateattributes(expectedvector, {expectedclasses}, {'column'});
Alternatively one could ensure that the code works whatever the shape of input:
guaranteedtobecolumn = anyshapeinput(:);
"one does not always check" is just poor practice and will lead to bugs.
Manuel
Manuel 2017 年 11 月 17 日
I totally agree with you. Nevertheless, it would not hurt if a.m. operation trows an error since it is easily corrected...

この質問は閉じられています。

Community Treasure Hunt

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

Start Hunting!

Translated by