[R] How to print matrices in standard format was ... Re: How to define new matrix based on an elementary row oper

David Winsemius dwinsemius at comcast.net
Mon Sep 13 00:46:03 CEST 2010


On Sep 12, 2010, at 12:24 PM, David Winsemius wrote:

>
> On Sep 12, 2010, at 11:27 AM, Cuckovic Paik wrote:
>
>>
>> I appreciate all you help. This is only for instructional purpose:
>>
>> A = matrix(c(0,1,1,-2,-3,1,2,-1,0,2,2,4,1,-3,-2,1,-4,-7,-1,-19),  
>> ncol=5,
>> byrow=T)
>> B  
>> = 
>> matrix(sample(c(0,1,1,-2,-3,1,2,-1,0,2,2,4,1,-3,-2,1,-4,-7,-1,-19),),
>> ncol=5, byrow=T)
>>
>> Which print func( A, B,  A+B) can print the resulting matrices A  
>> and B and
>> A+B  in the following format?
>>
>>    [,1] [,2] [,3] [,4] [,5]             [,1] [,2] [,3] [,4] [, 
>> 5]            [,1]  [,2]  [,3]  [,4] [,5]
>> [1,]    0    1    1   -2   -3       [1,]  2   -1    0    2      
>> 1        [1,]  2     0     1     0    -2
>> [2,]    1    2   -1    0    2   +   [2,]  1   -4    2   -2    -2    
>> =    [2,]  2    -2     1    -2     0
>> [3,]    2    4    1   -3   -2       [3,] -3    1   -7    1     
>> -1        [3,] -1     5    -6    -2    -3
>> [4,]    1   -4   -7   -1  -19       [4,] -3    0    4  -19      
>> 1        [4,] -2    -4    -3   -20   -18
>>
>
> for( i in 1:nrow(A) ) { cat(sprintf("%4.0f", A[i, ]), paste("   
> ",if( i==3 ){"+"}else{" "}, " ", sep=""),sprintf("%4.0f",B[i, ]),  
> paste("  ",if( i==3 ){"="}else{" "}, " ", sep=""), sprintf("%4.0f",  
> (A+B)[i, ]), "\n" )}
>
  for( i in 1:nrow(A) ) { cat(sprintf("%4.0f", A[i, ]),
                             paste("  ",if( i==3 ){"+"}else{" "}, " ",  
sep=""),
                             sprintf("%4.0f",B[i, ]),
                             paste("  ",if( i==3 ){"="}else{" "}, " ",  
sep=""),
                             sprintf("%4.0f", (A+B)[i, ]), "\n" )}

Even with the prettier printing it stilled seemed like a hack, so here  
is a grid graphics solution that gives prettier _output_:

require(grid)
 > grid.newpage()
 > pushViewport(plotViewport(c(5,4,2,2)))  # implicit limits are  
c(0,0,1,1) within plot area
 > for (i in 1:nrow(A)) { for (j in 1:ncol(A)){grid.text(A[i,j], x=i/ 
20, y=j/20)}}  # plot mtx A
 > for (i in 1:nrow(B)) { for (j in 1:ncol(B)){grid.text(B[i,j], x=(i 
+5)/20, y=j/20)}}  # B
 > for (i in 1:nrow(B)) { for (j in 1:ncol(B)){grid.text(A[i,j] 
+B[i,j], x=(i+10)/20, y=j/20)}} # A+B
 > grid.text("=", x=10/20, y=2.5/20)
 > grid.text("+", x=5/20, y=2.5/20)



>

--

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list