Different result when adding variables

1 回表示 (過去 30 日間)
Jim
Jim 2016 年 5 月 19 日
編集済み: Jim 2016 年 5 月 19 日
This is in MATLAB R2016a. The addition
1:3 + [0 0 5]
gives
1 2 3
if we assign
x = 1:3;
and
y = [0 0 5];
then x+y is
1 2 8

採用された回答

Stephen23
Stephen23 2016 年 5 月 19 日
編集済み: Stephen23 2016 年 5 月 19 日
You are doing two different operation sequences, so why the surprise that you get two different results?
First Case
>> 1:3 + [0 0 5]
ans =
1 2 3
because of the operator precedence (plus is higher than colon) is equivalent to
>> 1: (3 + [0 0 5])
ans =
1 2 3
which is equivalent to
>> 1:[3,3,8]
ans =
1 2 3
and thus is just
>> 1:3
ans =
1 2 3
because the colon operator only uses the first element of the vector and ignore the rest: "If you specify nonscalar arrays, MATLAB interprets j:i:k as j(1):i(1):k(1)."
Second Case
>> x = 1:3;
>> y = [0 0 5];
>> x+y
ans =
1 2 8
performs an element-wise addition on two vectors.
Summary
Beginners often forget about operator precedence and to read the documentation...
  2 件のコメント
Jim
Jim 2016 年 5 月 19 日
編集済み: Jim 2016 年 5 月 19 日
I just thought the colon operator had priority over the plus operator...
Summary: always use parentheses to be sure, especially if you are programming in different languages
Steven Lord
Steven Lord 2016 年 5 月 19 日
To elaborate slightly on Stephen's answer, the plus operator is at precedence level 6 while the colon operator is at level 7.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by