从 n,k 维矩阵数组中减去 n,k 维矩阵 [英] Subtract matrix of n,k dimensions from array of matrices of n,k dimensions

查看:32
本文介绍了从 n,k 维矩阵数组中减去 n,k 维矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个数组 A

A <- array(0, c(4, 3, 5))
for(i in 1:5) {
  set.seed(i)
  A[, , i] <- matrix(rnorm(12), 4, 3)
}

如果我有矩阵 B

set.seed(6)
B <- matrix(rnorm(12), 4, 3)

从数组 A 的每个矩阵中减去 B 的代码是:

The code to subtract B from the each matrix of the array A would be:

d<-array(0, c(4,3,5))
for(i in 1:5){
  d[,,i]<-A[,,i]-B
}

但是,使用apply"系列中的函数执行相同计算的代码是什么?

However, what would be the code to perform the same calculation using a function from "apply" family?

推荐答案

这就是 sweep 的用途.

sweep(A, 1:2, B)

这篇关于从 n,k 维矩阵数组中减去 n,k 维矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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