transport to matlab language

1 次查看(过去 30 天)
mar vouz
mar vouz 2016-4-26
STEP1: SET x=x0, SET i=0
STEP2: SET i=i+1
CALCULATE f(x)
CALCULATE f-­‐‑(x)= f(x-­‐‑h)
CALCULATE f+(x)= f(x+h)
CALCULATE f ’(x)=[f+(x)-­‐‑f-­‐‑(x)]/2h
STEP4: if f (x)=0 then {
if f(x) <= tol_root then goto 10 //success
else SET X=X0+h
}
STEP5: SET xnew=x-­‐‑f(x)/f (x)
STEP6: if i > imax then exit //failure
STEP7: if abs(xnew-­‐‑x) <= tol_x then goto STEP10 //success
else goto STEP8
STEP8: SET x=xnew
STEP9: goto STEP2
STEP10: exit
Can anyone help me with that? I have to transport this in matlab language in case to create a program

回答(1 个)

Walter Roberson
Walter Roberson 2016-4-26
while true
Do some things
if Condition
break
end
end
  2 个评论
mar vouz
mar vouz 2016-4-26
编辑:per isakson 2018-2-13
So I created the following code :
% code
x=0;
h=0.001;
tol_root=1e-05;
tol_x=1e-05;
for i = 1:1:50
f=@(x) x.^2 + 0.16*x -0.237;
fpl=@(x) f(x+h);
fout=@(x) f(x-h);
df=@(x) (fpl(x)-fout(x))/(2*h);
if df(x)==0 then
if f(x)<=tol_root
i=51;
else
x=x+h
end
end
xnew=x-f(x)/df(x);
if abs (xnew-x)<= tol_x
e(i)=@(x) abs(xnew-x)
i=51
else
x=xnew
end
end
xroot=xnew
And it actually gives me seven roots.But also it gives me this message:
The following error occurred converting from function_handle to double:
Error using double
Conversion to double from function_handle is not possible.
why?
Steven Lord
Steven Lord 2018-2-13
e is a double precision array. When you try to assign a function handle into it MATLAB tries to convert that function handle into a double precision value. It can't, that conversion isn't defined.
From context you don't want e to contain a function handle that computes the residual, you want it to contain the residual itself. Get rid of the @(x) on the line where you assign to e(i).
But there are other problems or areas for improvement with this code. Two I see off the top of my head:
Assigning a value to the for loop variable will change the value of that variable for the rest of that iteration of the for loop. When MATLAB goes back to the top, your modified value is thrown away and replaced by the next iterate. This is described in the second item of the Tips section on the for documentation page. So your attempt to exit the loop with "i = 51" won't work.
To exit out of a for loop early, use the break keyword as suggested by the first item of the Tips section on the for documentation page.
Since your functions f, fpl, fout, and df don't depend on any variables that change inside the for loop, it will be more efficient to define them outside the loop. [Probably not much more efficient, but why define the same thing 50 times when you can define it once?]

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by