Help displaying a formatted matrix to the command window
Afficher commentaires plus anciens
Hi all, this seems like a simple question, but sprintf(...) doesn't do the trick. Is there an EASY way to display a matrix in the command window with a specified number of digits of precision?
EXAMPLE:
>> x = rand(3,2) - 0.5
x =
-0.3810 -0.1596
-0.0016 0.0853
0.4597 -0.2762
>> format long >> x
x =
-0.381002318441623 -0.159614273333867
-0.001635948017857 0.085267750979777
0.459743958516081 -0.276188060508863
How do I show x with, say, 6 digits of precision (as in below)??
-0.381002 -0.159614
-0.001635 0.085267
0.459743 -0.276188
I'm sure one could write a code that figured out the size of x and then used sprintf to create the desired output. Does this code exist?
Réponse acceptée
Plus de réponses (2)
Oleg Komarov
le 5 Juin 2012
sprintf('%.6f %.6f\n',rand(3,2))
Edited
Now, if you wanna make the number of columns adjust automatically, then:
A = randn(3,9);
sprintf([repmat('%10.6f',1,size(A,2)) '\n'],A)
Unfortunately, there's some learning curve in format customization.
7 commentaires
Brenden Epps
le 5 Juin 2012
Oleg Komarov
le 5 Juin 2012
I edited the second solution, now it's correct.
Brenden Epps
le 6 Juin 2012
Oleg Komarov
le 6 Juin 2012
A = randn(3,9);
sprintf([repmat('%10.6f',1,size(A,2)) '\n'],A)
Have you tried it?
You can tweak the %10 to give more space between the numbers.
Jan
le 6 Juin 2012
+1: I still prefer the REPMAT approach. And if the minus character matters, I'd use the '+' specification and replace the '+' by spaces:
A = 1 - randn(3,9); fprintf(strrep(sprintf([repmat('%+10.6f',1,size(A,2)) '\n'],A), '+', ' '));
Anton
le 10 Oct 2018
It seems that this one transposes my matrix in the process though
@Anton: yes, all of the above examples should transpose the array, like this:
fprintf(...,A.')
The fprintf help explains that it "...applies the formatSpec to all elements of arrays A1,... An in column order, and writes the data..." (emphasis added).
Walter Roberson
le 10 Oct 2018
Try
num2str(x, 6)
Catégories
En savoir plus sur Logical dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!