【问题标题】:Forcing matrix to have even dimensions without conditional强制矩阵在没有条件的情况下具有偶数维度
【发布时间】:2017-07-10 06:10:28
【问题描述】:

我正在寻找一种巧妙的方法来强制矩阵的维度(nrow 和 ncol)均匀不使用 if 语句force 我的意思是减去第一个适当的列和/或行,以便两个维度都是偶数。

我希望这样的事情会起作用:

 ## 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]

显然最后一行没有给出想要的结果。有没有不使用条件的聪明方法?

【问题讨论】:

  • x.even = x[1:(2*floor(nrow(x)/2)),1:(2*floor(ncol(x)/2))]
  • 我喜欢它!干杯!

标签: r matrix indexing


【解决方案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

【讨论】:

    【解决方案2】:

    只需将nrowncol 除以2,取floor,再乘以2

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

    【讨论】:

      猜你喜欢
      • 2017-10-22
      • 2018-01-18
      • 2019-12-06
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多