How can I re write this but with a different variable other than "syms"
Show older comments
syms x;
syms f(x);
% average of las 4 digitss
avg=4;
% get gama value
gama=5+avg;
% 5% relative error
err=5/100;
% defining the function
f(x)=(log(x)/log(exp(1)))*sin(x^2/(5*gama));
% lower limit of x
a=1;
% upper limit of x
b=11;
% goldain ratio
gr=(sqrt(5)+1)/2;
% new value for c and d using golden ratio , and
c=b-(b-a)/gr;
d=a+(b-a)/gr;
% to store number of iteration
itr=0;
% loop until opto 5% relative error
while abs((b-a)/a)>=err || abs((b-a)/b)>=err
% get functional value of c and d
val1=eval(f(c));
val2=eval(f(d));
% set new a or new b
if val1<val2
b=d;
else
a=c;
end
c=b-(b-a)/gr;
d=a+(b-a)/gr;
% increase iteration
itr=itr+1;
end
fprintf('Boundary is [ %.6f , %.6f ] after iteration %d\n',a,b,itr);
op_val=(a+b)/2;
fprintf('Optimal solution is %.6f\n',op_val);
I need to re-write this code without using the functions syms cause I do not have that for my matlab version.
1 Comment
Helen Liao
on 26 Feb 2021
Edited: Helen Liao
on 26 Feb 2021
Hi Owen,
I think there are two ways you can use
- you can use function handle to do the same thing, and here is the doc link - https://www.mathworks.com/help/matlab/matlab_prog/creating-a-function-handle.html. For example, create a function handle like this in your script.
sqr = @(n) n.^2;
x = sqr(3)
- Create a function to put your formula, and here is the doc link - https://www.mathworks.com/help/matlab/ref/function.html. just call the function in your script. Please be aware you need to put function in the same directory with your scrip or add the function to your path when you run your script. Otherewise it might not be able to find the function. Function example is like the following:
function ave = average(x)
ave = sum(x(:))/numel(x);
end
Hope those two methods could help you.
Thanks,
Helen
Answers (1)
% average of las 4 digitss
avg=4;
% get gama value
gama=5+avg;
% 5% relative error
err=5/100;
% defining the function
f = @(x) (log(x)./log(exp(1))).*sin(x.^2/(5*gama));
% lower limit of x
a=1;
% upper limit of x
b=11;
% goldain ratio
gr=(sqrt(5)+1)/2;
% new value for c and d using golden ratio , and
c=b-(b-a)/gr;
d=a+(b-a)/gr;
% to store number of iteration
itr=0;
% loop until opto 5% relative error
while abs((b-a)/a)>=err || abs((b-a)/b)>=err
% get functional value of c and d
val1 = f(c);
val2 = f(d);
% set new a or new b
if val1<val2
b=d;
else
a=c;
end
c=b-(b-a)/gr;
d=a+(b-a)/gr;
% increase iteration
itr=itr+1;
end
fprintf('Boundary is [ %.6f , %.6f ] after iteration %d\n',a,b,itr);
op_val=(a+b)/2;
fprintf('Optimal solution is %.6f\n',op_val);
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!