How should I write this fprintf in order for it to work?
2 次查看(过去 30 天)
显示 更早的评论
I have this:
lambda=2;
fprintf(['%%%%%%%%%%%%%%%'...
' lambda=%d '...
'%%%%%%%%%%%%%%%\n'],lambda)
fprintf('%%%%%%%%%%lambda=%d %%%%%%%%%%%%%%%%%\n',lambda)
Neither of them seem to work. If I write them separately, the first one doesn't give the answer because it cuts it. The second gives the answer but doesn't display all the characters '%' I have written at the end. Plus, if they are together, only the second one works (partly, as I've described).
What should I do in order for them to work (together and separately)?
PS: I want to use the first fprintf in this program:
clear, format compact, format shortg
myoptions=optimoptions('fsolve','tolx',1e-12,'maxiter',100,'display','off');
for lambda=0:2
fprintf(['%%%%%%%%%%%%%%%'...
' lambda=%d '...
'%%%%%%%%%%%%%%%\n'],lambda)
[x,fval,exitflag]=fsolve(@(x)a57fun(x,lambda),rand(3,1),myoptions)
fprintf(['El valor de x(2) con 8 cifras significativas'...
'para lambda=%d es %1.8f \n'],lambda,x(2))
end
function [F]=a57fun(x,lambda)
A=[6 -1 2; -1 4 3; 2 3 5];
ter1=exp(2*x(1)^2+x(2)^2-1);
ter2=sinh(5*x(2)-x(3));
g=[4*x(1)*ter1; 2*x(2)*ter1+5*ter2; -ter2];
b=[1;2;3];
F=A*x+lambda*g-b;
end
0 个评论
采纳的回答
Stephen23
2016-5-6
编辑:Stephen23
2016-5-6
Beginners often complain that some function "does not work" properly, and very often they did not bother to read the documentation. When you read the fprintf documentation then you will learn that '%' is a special character that needs special handling (called escaping).
Hint: the documentation tells us how MATLAB works: use it.
Both of these examples show print ten % characters in a row, and none of them disappear!
Solution One: Escape the Format String Properly
lambda=2;
fmt = repmat('%%',1,10);
fmt = sprintf('%s lambda = %%d %s\\n',fmt,fmt);
fprintf(fmt,lambda)
prints this:
%%%%%%%%%%lambda = 2 %%%%%%%%%%
Solution Two: use Input Arguments Properly
lambda=2;
fmt = repmat('%',1,10);
fprintf('%s lambda = %d %s\n',fmt,lambda,fmt)
prints
%%%%%%%%%%lambda = 2 %%%%%%%%%%
更多回答(1 个)
Azzi Abdelmalek
2016-5-6
编辑:Azzi Abdelmalek
2016-5-6
lambda=2;
fprintf('%%%%%%%%%% lambda=%d %%%%%%%%%%\n',lambda)
The number of % should be even. Because to display the special character %, you need to represent it with %%
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Identification 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!