Change a variable in a function.

Im using the fsolve function inside a loop and there is an integer inside the fsolve function that will change the solution of the fsolve, i want to increment that number each time the loop is conducted, i defined the term in global and gave it a value of 1 intially, then i tried using A=A+1 inside the loop but the fsolve gave me the final answer only to that equation and i tried putting the A=A+1 inside the function but it gave me an error.

回答 (1 件)

Nicolas B.
Nicolas B. 2019 年 11 月 28 日

0 投票

I never tried with global variables but, in your case, I would recommend you to set your A has an input. What I understand, all variables which are not inputs of the function_handle are set as constant in the function_handle when you define it (but I could be wrong). So I would recommand to define your function handle as:
A = 1;
f = @(in1, in2, A) you_function(in1, in2, A);
while your_condition
f(in1, in2, A);
A = A + 1;
end

9 件のコメント

Anas Albizreh
Anas Albizreh 2019 年 11 月 28 日
Its telling me Undefined function or variable 'A'.
Nicolas B.
Nicolas B. 2019 年 11 月 28 日
Can you add here your code please?
Anas Albizreh
Anas Albizreh 2019 年 11 月 28 日
I called it C here.
Rik
Rik 2019 年 11 月 28 日
編集済み: Rik 2019 年 11 月 28 日
This time I edited your comment for you. Next time, please use the tools explained on this page to make your code more readable.
Anas Albizreh
Anas Albizreh 2019 年 11 月 28 日
Sorry im new here.
Anas Albizreh
Anas Albizreh 2019 年 11 月 29 日
Help me please.
Nicolas B.
Nicolas B. 2019 年 11 月 29 日
You should add A to the input of func() and myfunc().
If I could give you a general advice, try to avoid as much as possible the global variables. It makes your script impossible to re-use and difficult to debug.
Anas Albizreh
Anas Albizreh 2019 年 11 月 29 日
Can you tell me how to do it, i tried doing it but it didn't work.
Nicolas B.
Nicolas B. 2019 年 11 月 29 日
I don't have the optimization toolbox, so I cannot test it, but it should work like that (only the necessary code is shown:
global U Lg L2 L3 L4 L1 Th1 Th2
...
x0 = [deg2rad(145), deg2rad(20)];
x = fsolve(@(x) myfunc(x, A),x0);
...
function F = myfunc(X, A)
global U Lg
thA = X(1);
th2 = X(2);
F(1) = real( U*exp(1i*th2)-A*exp(1i*thA)-Lg );
F(2) = imag( U*exp(1i*th2)-A*exp(1i*thA)-Lg );
end

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

カテゴリ

ヘルプ センター および File ExchangeFunction Creation についてさらに検索

製品

リリース

R2018a

質問済み:

2019 年 11 月 28 日

コメント済み:

2019 年 11 月 29 日

Community Treasure Hunt

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

Start Hunting!

Translated by