[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
Sun Sep 12 18:24:10 CEST 2010


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" )}

-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list