2014-07-08 259 views
0

尋找一種將矩陣映射到邏輯矩陣的優雅方式。 例如,如果n[i,j] >= 10應當映射到1,否則爲0。將矩陣映射到邏輯矩陣

12 34 3 4 10 
11 1 3 4 6 
2 34 4 3 22 

應被映射:

1 1 0 0 1 
1 0 0 0 0 
0 1 0 0 1 

回答

1

隨着ifelse

x <- matrix(c(12, 34, 3, 4, 10, 11, 1, 3, 4, 6, 2, 34, 4, 3, 22), 3, 5, byrow=TRUE) 
ifelse(x >= 10, 1, 0) 
    [,1] [,2] [,3] [,4] [,5] 
[1,] 1 1 0 0 1 
[2,] 1 0 0 0 0 
[3,] 0 1 0 0 1 
+1

另外'(X> = 10)+ 0' – thelatemail

+0

@thelatemail,沒有看到您的解決方案。我已經發布了它。 – akrun

1

這應該是一樣簡單:

mat <- your.mat >= 10 
mat[] <- as.numeric(mat) # the `[]` on the LHS preserves the structure. 

例如

> mat <- matrix(sample(1:20,16),4) >5 
> mat[] <- as.numeric(mat) 
> mat 
    [,1] [,2] [,3] [,4] 
[1,] 1 0 0 1 
[2,] 1 1 1 1 
[3,] 1 0 1 1 
[4,] 1 1 0 1 
3

如果x是矩陣

(x>=10)*1 
#  [,1] [,2] [,3] [,4] [,5] 
#[1,] 1 1 0 0 1 
#[2,] 1 0 0 0 0 
#[3,] 0 1 0 0 1 

或者

(x>=10)+0