How should I write this fprintf in order for it to work?
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Ricardo Boza Villar
le 6 Mai 2016
Commenté : Ricardo Boza Villar
le 6 Mai 2016
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 commentaires
Réponse acceptée
Stephen23
le 6 Mai 2016
Modifié(e) : Stephen23
le 6 Mai 2016
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 %%%%%%%%%%
Plus de réponses (1)
Azzi Abdelmalek
le 6 Mai 2016
Modifié(e) : Azzi Abdelmalek
le 6 Mai 2016
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 %%
Voir également
Catégories
En savoir plus sur Data Type Identification dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!