Efficient way to solve an equation in MATLAB

조회 수: 8 (최근 30일)
Ali Almakhmari
Ali Almakhmari 2022년 9월 25일
댓글: Dyuman Joshi 2022년 9월 26일
I have a nested for loop system that will run 251658240...you heard me correctly. There isn't much in this for loop that is time-consuming, except solving this equation: where "x" is a costant that changes with each iteration. The method I am using right now is
syms theta
theta = vpasolve((2*theta + sin(2*theta))==(pi*sin(x)));
Is there a way to make this solving process faster? Cause its soooo time-consuming doing it this way

채택된 답변

Steven Lord
Steven Lord 2022년 9월 25일
Solve numerically using fzero. Here I've written a function handle that itself makes function handles. I can pass that generated function handle into fzero to get a solution.
f = @(x) @(theta) 2*theta + sin(2*theta) - (pi*sin(x));
h = f(1) % h "remembers" that x is 1
h = function_handle with value:
@(theta)2*theta+sin(2*theta)-(pi*sin(x))
sol = fzero(h, 1)
sol = 0.8232
Check the solution
h(sol) % Should be close to 0
ans = 0
Or check explicitly, if the way f creates a function handle looks like "magic".
2*sol + sin(2*sol) - pi*sin(1)
ans = 0
If you're going to solve this repeatedly for potentially the same value of x, you may also want to memoize h.
  댓글 수: 3
Steven Lord
Steven Lord 2022년 9월 25일
That works if x has been defined before you create the function handle, but note that changing the value of x after the function handle has been created does not change the function handle.
x = 1;
f = @(y) x+y;
f(2) % 3
ans = 3
x = 999;
f(2) % still 3 not 1002
ans = 3
Dyuman Joshi
Dyuman Joshi 2022년 9월 26일
Yes, I am aware of that. However, what would be the difference between -
f = @(x) @(theta) 2*theta + sin(2*theta) - (pi*sin(x));
h = f(1) % h "remembers" that x is 1
h = function_handle with value:
@(theta)2*theta+sin(2*theta)-(pi*sin(x))
sol = fzero(h, 1)
sol = 0.8232
F = @(x,theta) 2*theta + sin(2*theta) - (pi*sin(x));
fzero(@(theta) F(1,theta),1)
ans = 0.8232

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

태그

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by