How do I change a function name within a loop using variables?

11 ビュー (過去 30 日間)
Sarath S
Sarath S 2019 年 8 月 17 日
コメント済み: Stephen23 2019 年 8 月 17 日
I am trying to write a function that returns the root of a polynomial using Mullers method. I want the user to choose between the 2 polyomials shown in comment.
I am using two other functions 'poly1' and 'poly2' which returns the value of the polynomial for x.
How do i call 'poly1' or 'poly2' from within the for loop depending on the users choice? Is there any way to have a variable at the end of poly like poly'i' that changes to 1 or 2? Thanks
  1 件のコメント
Rik
Rik 2019 年 8 月 17 日
One of the concerns is trusting user input. You should always write your code as if your user is either incompetent or out to do malice.

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

採用された回答

Stephen23
Stephen23 2019 年 8 月 17 日
編集済み: Stephen23 2019 年 8 月 17 日
You can store function handles in a cell array and use indexing:
>> C = {@(x)2*x+3,@(x)sqrt(x)+1}; % {1st fun,2nd fun}
>> C{1}(2) % 1st function evaluated with x=2
ans = 7
>> C{2}(2) % 2nd function evaluated with x=2
ans = 2.414213562373095
"Is there any way to have a variable at the end of poly like poly'i' that changes to 1 or 2?"
You could use str2func, but I doubt that it would result in simple, efficient, or reliable code.
  2 件のコメント
Sarath S
Sarath S 2019 年 8 月 17 日
編集済み: Sarath S 2019 年 8 月 17 日
Thanks a lot.
Will it work if the user chooses ch = 1 and I use c{ch} to get the 1st function?
Edit
It works! Thanks again.
Stephen23
Stephen23 2019 年 8 月 17 日
"Will it work if the user chooses ch = 1 and I use c{ch} to get the 1st function?"
Yes. That is how indexing works.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeVariables についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by