Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

how to printf a matrix like this

by madM (Beadle)
on Feb 11, 2014 at 10:48 UTC ( [id://1074381]=perlquestion: print w/replies, xml ) Need Help??

madM has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks! Iīm trying to print a 4 x 4 matrix but i donīt really know how to round the numbers and print them at the same time with printf with a spacing of ,for example, 4 Hereīs what i wrote: the numbers are stored in a hash of hashes with the keys A B C and D
A => A 6.8888 B => B 6.8888 C => C 6.8888 D => D 6.8888
the rest of the numbers are 0.1111
my @letters=qw(A B C D); print ' '; foreach my $key (@letters){ printf ("%s", $key); } "\n"; foreach my $key (@letters) { print $key,' '; foreach my $key2 (@letters) { printf ("%.1f" , $A->{$key}->{$key2}); } print "\n"; } }
Hereīs what im trying to get:
A B C D A 6.8 0.1 0.1 0.1 B 0.1 6.8 0.1 0.1 C 0.1 0.1 6.8 0.1 D 0.1 0.1 0.1 6.8

Replies are listed 'Best First'.
Re: how to printf a matrix like this
by RichardK (Parson) on Feb 11, 2014 at 11:46 UTC

    The explanation of how to use printf formatting is in the help for sprintf. (the printf help really should point to this too).

    To fix your problem you need to set a minimum width, try something like this :-

    printf "%6.1f",$var;
      "The explanation of how to use printf formatting is in the help for sprintf. (the printf help really should point to this too)." [my emphasis]

      The printf documentation does point to this. It starts with:

      "Equivalent to print FILEHANDLEsprintf(FORMAT, LIST), ..."

      [FWIW, madM has already been provided with that information (in Re: printf matrix) as well as example sprintf usage in a number of places.]

      -- Ken

      thakyou! that really helped :)
Re: how to printf a matrix like this
by Anonymous Monk on Feb 11, 2014 at 11:11 UTC
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: how to printf a matrix like this
by McA (Priest) on Feb 11, 2014 at 11:09 UTC

    Hi,

    IMHO the most generic approach would be to store the result matrix into an array of arrays. While doing so, you could remember the most needed space for a column. After that you know the minimum space for each column and the adjustment needed when printing. After that you print each row of the array of arrays knowing how to adjust the length of the output.

    Regards
    McA

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1074381]
Approved by rnewsham
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-04-25 19:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found