MATLAB Answers

# How can I re write this but with a different variable other than "syms"

18 views (last 30 days)
Owen Fernandez on 24 Feb 2021
Answered: Walter Roberson on 26 Feb 2021
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 CommentShowHide None
Helen Liao on 26 Feb 2021
Hi Owen,
I think there are two ways you can use
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

Sign in to comment.

### Answers (1)

Walter Roberson on 26 Feb 2021
% 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);
Boundary is [ 1.000000 , 1.031056 ] after iteration 12
op_val=(a+b)/2;
fprintf('Optimal solution is %.6f\n',op_val);
Optimal solution is 1.015528
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

R2020b

### Community Treasure Hunt

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

Start Hunting!