2017-02-20 27 views
2

即使尺寸我要尋找一個聰明的方式來矩陣的尺寸(包括nrow和NcoI),甚至可以說不使用if語句。通過我的意思是減去第一個適當的列和/或行,使兩個維度均勻。強制矩陣有沒有條件

我希望像這樣的工作:

## build a matrix with odd number of columns and even number of rows 
x=matrix(1:12,nrow=4,ncol=3) 

## we can check which (if any) dimensions are odd with 
dim(x) %% 2 ## 0,1 

## I would like get a matrix that looks like 
     [,1] [,2] 
[1,] 5 9 
[2,] 6 10 
[3,] 7 11 
[4,] 8 12 

## By using something similar to 
x.even = x[-nrow(x)%%2,-ncol(x)%%2] 

顯然最後一行沒有給出期望的結果。有沒有一種聰明的方式來做到這一點,而不使用條件?是建立在您的解決方案

+1

乘'x.even = x [1:(2 * floor(nrow(x )/ 2)),1 :(2 * floor(ncol(x)/ 2))]' –

+1

我喜歡它!乾杯! –

回答

1

只是劃分nrowncol通過2,採取floor,並通過2再次

x.even = x[1:(2*floor(nrow(x)/2)),1:(2*floor(ncol(x)/2))] 
1

方式一:

#start rows and columns from 1 
#also subtract remainder from total rows and columns 
x[1:(nrow(x) - nrow(x) %% 2), 1:(ncol(x) - ncol(x) %% 2)] 

輸出:

 [,1] [,2] 
[1,] 1 5 
[2,] 2 6 
[3,] 3 7 
[4,] 4 8