如何计算3D阵列切片上的表达式? [英] How could I calculate an expression across the slices of a 3D-array?

查看:72
本文介绍了如何计算3D阵列切片上的表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经针对24x24方阵(a)的每24个值计算了该hc指数.它会返回具有24个值的向量(hc).

I have calculated this hc index for every 24 values of a 24x24 square matrix (a). It returns a vector (hc) with 24 values.

hc<-vector("numeric",24L)
for (i in 1:24) {
  hc[i]<- -sum((c(a[,i])/colSums(a)[i])*log((c(a[,i])/colSums(a)[i]), base = 2))
  }

我想为数组的1000个矩阵中的每个矩阵计算此函数,并且不知道确切地如何进行处理(一个函数?另一个嵌套的"for"语句?...).并获得1000个24个长度的向量.数组中每个矩阵一个.我真的很感谢您的帮助.谢谢!

I want to calculate this for each of the 1000 matrices of an array and don't know exactly how to proceed (a function?, another nested "for" statement?...). And get 1000, 24length vectors. One for each matrix in the array. I would really appreciate any help. Thanks!

推荐答案

如果您实际上有一个数组,这是另一种方法:

Here's an alternative approach, if you actually have an array:

# Simplified version of your function
f <- function(x) -sum(x / sum(x) * log2(x / sum(x)))

set.seed(1)
n <- 1000

matrices <- replicate(n, matrix(runif(24 ^ 2), nrow = 24))
str(matrices)
#>  num [1:24, 1:24, 1:1000] 0.266 0.372 0.573 0.908 0.202 ...

result <- apply(matrices, c(2, 3), f)
str(result)
#>  num [1:24, 1:1000] 4.36 4.36 4.37 4.36 4.34 ...

如果您的矩阵在列表中:

If your matrices are in a list:

matrix_list <- lapply(seq_len(n), function(i) matrices[, , i])
list_result <- lapply(matrix_list, apply, 2, f)
str(head(list_result))
#> List of 6
#>  $ : num [1:24] 4.36 4.36 4.37 4.36 4.34 ...
#>  $ : num [1:24] 4.43 4.32 4.31 4.4 4.37 ...
#>  $ : num [1:24] 4.26 4.21 4.31 4.24 4.24 ...
#>  $ : num [1:24] 4.31 4.36 4.27 4.32 4.35 ...
#>  $ : num [1:24] 4.39 4.27 4.35 4.29 4.22 ...
#>  $ : num [1:24] 4.25 4.42 4.19 4.32 4.33 ...

reprex程序包(v0.2.0)创建于2018-03-05.

Created on 2018-03-05 by the reprex package (v0.2.0).

这篇关于如何计算3D阵列切片上的表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆