Using loops to perform vector functions

1 回表示 (過去 30 日間)
Jonathan Lam
Jonathan Lam 2022 年 1 月 26 日
コメント済み: Rik 2022 年 1 月 26 日
I'm new to MATLAB and I'm having trouble with my function. I'm trying to call upon a different operation "op" to do subtraction instead of addition but despite entering op as 2 it's still doing addition. Any help is greatly appreciated.
  3 件のコメント
Jonathan Lam
Jonathan Lam 2022 年 1 月 26 日
I set a2=[4 5 6 ] and the function worlks for addition. I'm not sure why subtraction isn't working.
Torsten
Torsten 2022 年 1 月 26 日
You set op=1 within the function.

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

採用された回答

Rik
Rik 2022 年 1 月 26 日
There is an mlint warning on line 7. If you hover your mouse over it, you will see a message that this input is not being used.
If you remove line 10, the op input will be used, and the code should work as expected.
  2 件のコメント
Jonathan Lam
Jonathan Lam 2022 年 1 月 26 日
Thank you so much, one line of code can drive someone crazy!
Rik
Rik 2022 年 1 月 26 日
It is a good habit to always make sure there are no mlint warnings. If you are 100% sure the warning isn't a problem, you rightclick to add %#ok with a specific flag. This will hide that specific warning on that specific line. That way you can easily see if you made another mistake on the same line.
The added benifit of doing it that way: if the reason for the mlint warning disappears, you get a new warning. So if you make a mistake, that will still show up.

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

その他の回答 (1 件)

KSSV
KSSV 2022 年 1 月 26 日
In the function you have given input op which decides wheter to add ot subtract. But you are over writitng the input op inside the code to op = 1. So always the function adds. You need to remove the line op = 1 i.e. ine number 10 in the code.
Also your variable result has to be intiailized before the loop.
  1 件のコメント
Jonathan Lam
Jonathan Lam 2022 年 1 月 26 日
Great catch, thank you so much!

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by