how to use fprintf in string command
2 次查看(过去 30 天)
显示 更早的评论
Hello everyone, I want to ask a question about using fprintf in string command. I have arranged a code to calculate minimum value of a function using hooke jeeves method (optimization problem). Here is the code :
clear all clear clc
% HOOKE-JEEVES (for 2 variables):
rasio = 0.6; x = [1 7]; delx = [0.1 0.1]; tol = [0.001 0.001]; n=length(x); Fopt=fungsi(x(1),x(2)); xopt=x;F=Fopt; disp([xopt Fopt])
%checking delta
chekdel=strcat('if delx(1)<=tol(1)&delx(2)<=tol(2);','disp([xopt Fopt]);'... ,'disp(delx);','else;','del=delx*rasio;','delx=del;','eval(eksplorasi);'... ,'end;');
%repeating success step
ulsuk=strcat('while Fopt<F;','disp([xopt Fopt]);','for i=1:n;',... 'x(i)=xopt(i)+delx(i)*tanda(i);','end;','F=fungsi(x(1),x(2));',... 'if F<=Fopt;','xopt=x;', 'Fopt=F;','else;','break;','end;','end;',... 'eval(eksplorasi)');
%exploration:
eksplorasi=strcat('for ep=1:n;','tanda(ep)=0;','x(ep)=xopt(ep)+delx(ep);',... 'Fd=fungsi(x(1),x(2));','if Fd<=Fopt;','xopt(ep)=x(ep);','Fopt=Fd;','tanda(ep)=1;',... 'else;','x(ep)=xopt(ep)-delx(ep);','Fd=fungsi(x(1),x(2));','if Fd<=Fopt;',... 'xopt(ep)=x(ep);','Fopt=Fd;','tanda(ep)=-1;','end;','end;','end;','disp([xopt Fopt]);',... 'if abs(tanda(1))>0|abs(tanda(2))>0;','eval(ulsuk);','else;','eval(chekdel);',... 'end;'); eval(eksplorasi);
function f=fungsi(x1,x2) f=(x1-3)^2+((x2-5)^2)/4+7.5; end
The code written above works well. What i want here is that I want to use fprintf instead of disp. But, the code won't work when I replace the disp command with fprintf command. Anyone can help me solve my problem ?
Thank you
Andika
1 个评论
Jan
2012-7-16
编辑:Jan
2012-7-16
Please follow the "About Matlab Answers" link to learn more about the forum standards, e.g. the formatting of code. Thanks.
I strongly recommend not to create complicated strings and evaluate them using the evil EVAL. This is a bad bad bad programming style and ugly to debug. It is much nicer, smarter, more elegant, faster and cleaner to write commands as commands. Then you could even add comments, which explain your code.
Note: I haven't seen any case, which really required EVAL, and all workarounds have been big advantages in any case.
Another hint: "clear all" removes all loaded functions from the memory, and reloading them wastes a lot of time without any benefit. Even a "clear variables", which removes existing variables only, is a brute act and really serious bugs should be cauhgt by smarter techniques. It is like removing and reinserting the battery from your clock before you check the time.
回答(2 个)
Julian
2012-7-16
I guess you appreciate fprintf(1,f,x) can be used as a replacement for disp(x) but the format string fmt e.g. '%s\n' or '%d\n' must be chosen according type of x.
3 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!