2014-07-10 114 views
0

我將一個單元陣列轉換爲R. 在MATLAB中我使用x = cell(10,n)。我想要爲每個單元分配一個矩陣,如下所示:將matlab中的單元陣列轉換爲R中的列表

for i in 1:10 
for j in 1:n 
x(i,j) = [i*ones(len,1), ones(len,j)] 

這裏就像列數。 如何在R中執行此操作? 我試過列表中的R,我猜這個x看起來像包含10個列表,每個列表有n個子列表,每個子列表都有一個矩陣。它是否正確?

pic顯示在Matlab .n = 7中生成的第一個循環。第一行包含每個單元格中的一個數字矩陣。 我希望得到的是能夠通過使用獲得的第一矩陣「3×10雙」

x[1][1] in R 

Refence how to calculate the mean of list of list of matrices in r

This is from Matlab

答:根據上面的代碼的鏈接是一樣的東西:

x<-NULL 
for (i in 1:10){ 
    test<-NULL 
for (j in 1:n){ 
     test[[j]]<-matrix 
    } 
x[[i]]<-test 
} 
+0

這真是令人困惑。你想要什麼作爲輸出? – thelatemail

+0

@thelatemail請看照片,謝謝! – EskimoT

+0

那張照片從哪裏來?那是matlab代碼? R沒有單元陣列。您不能在正常矩陣內存儲矩陣。你可以創建一個列表矩陣,但這些並不總是很容易處理。 – MrFlick

回答

0
x<-NULL 
for (i in 1:10){ 
    test<-NULL 
for (j in 1:n){ 
     test[[j]]<-matrix 
    } 
x[[i]]<-test 
} 
0

第一,指定輸出中的行數和列數,並定義一個函數返回輸出矩陣中每個元素的內容。

n_rows <- 5 
n_cols <- 7 
get_element <- function(i, j) 
{ 
    len <- 10 
    cbind(rep.int(i, len), matrix(1, len, j)) 
} 

我們需要將所有行和列值的所有組合傳遞給函數。

index <- arrayInd(seq_len(n_rows * n_cols), c(n_rows, n_cols)) 

現在我們調用get_element和每個這些行/列對。

result <- mapply(get_element, index[, 1], index[, 2]) 

result是一個列表。這意味着它是一個向量,每個元素可以包含不同的值。爲了得到你想要的,你可以設置這個列表的尺寸。

dim(result) <- c(n_rows, n_cols) 

result 
##  [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  
## [1,] Numeric,20 Numeric,30 Numeric,40 Numeric,50 Numeric,60 Numeric,70 Numeric,80 
## [2,] Numeric,20 Numeric,30 Numeric,40 Numeric,50 Numeric,60 Numeric,70 Numeric,80 
## [3,] Numeric,20 Numeric,30 Numeric,40 Numeric,50 Numeric,60 Numeric,70 Numeric,80 
## [4,] Numeric,20 Numeric,30 Numeric,40 Numeric,50 Numeric,60 Numeric,70 Numeric,80 
## [5,] Numeric,20 Numeric,30 Numeric,40 Numeric,50 Numeric,60 Numeric,70 Numeric,80 

單個矩陣可以通過例如result[[3, 5]]進行訪問。

result[[3, 5]] 
##  [,1] [,2] [,3] [,4] [,5] [,6] 
## [1,] 3 1 1 1 1 1 
## [2,] 3 1 1 1 1 1 
## [3,] 3 1 1 1 1 1 
## [4,] 3 1 1 1 1 1 
## [5,] 3 1 1 1 1 1 
## [6,] 3 1 1 1 1 1 
## [7,] 3 1 1 1 1 1 
## [8,] 3 1 1 1 1 1 
## [9,] 3 1 1 1 1 1 
## [10,] 3 1 1 1 1 1 

請注意,儘管具有維度的列表與MATLAB單元格數組最接近,但它是一種很少使用的數據結構。這意味着你不會用這樣的結構編寫慣用的R代碼。 (從MATLAB編碼到R編碼的最大精神轉變之一是從矩陣方面的思考轉向考慮矢量方面)

在這種情況下,顯而易見的問題是「爲什麼你需要存儲所有這些矩陣嗎?「。只需撥打get_element並根據需要檢索值可能會更容易。