Using the disp command to print an answer in a particular format

24 visualizzazioni (ultimi 30 giorni)
I am a student at a university taking a computational methods class. We were assigned to write an equation to display the first sixteen Fibonacci numbers. The results were to printed using fprintf and using the display command. The fprintf command I have printed the results fine. I then set a variable equal to the fprintf command and entered disp(variable).It displays everything fine except at the end it displays a number 192 is there a way to suppress that number at the end any help would be appreciated.
I actually figured out that variable named after the fprintf command was wrong. So I entered disp(F') with F being the fibonacci function it displays the ans. in a column like I wanted. But I also wnat to print F(0) through F(15) in front of the answer on the display command. Here is my code so far.
n=(0:1:15); F=1/sqrt(5)*[((1+sqrt(5))/2).^n-((1-sqrt(5))/2).^n];
fprintf('F(%2.0f)=% -5.0f\n',[n;F]);
disp(' ')
disp(' ')
disp(F')
Any help would be greatly appreciated.

Risposta accettata

Walter Roberson
Walter Roberson il 20 Gen 2012
Use sprintf() instead of fprintf(). sprintf() returns the string, but fprintf() does the printing and then returns the number of characters output.
  5 Commenti
Adam Anderson
Adam Anderson il 20 Gen 2012
Thank you very much Walter I think I got it thanks to your advice with sprintf. The final code looks like this.
n=(0:1:15);
F=1/sqrt(5)*[((1+sqrt(5))/2).^n-((1-sqrt(5))/2).^n];
fprintf('F(%2.0f)=% -5.0f\n',[n;F]);
disp(' ')
disp(' ')
x=sprintf('F(%2.0f)=% -5.0f\n',[n;F]);
disp(x)
Once again thanks for your time, patience and contributions to a noob.
Walter Roberson
Walter Roberson il 20 Gen 2012
Though probably they intended you to loop and use string concatenation, the point being to show how much easier that fprintf() is.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by