如何处理"非顺应性"数组? [英] How to deal with "non-conformable" arrays?

查看:125
本文介绍了如何处理"非顺应性"数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个人如何做逐元素算术运算的两个数组,其
贴合在第一维度,但一个人也一个额外的维度?

How does one do element-wise arithmetic operations with two arrays that are conformable in the first dimensions but one has also an extra dimension?

为例,乘以阵列 A (3×3×2)阵列 B (3×3):

Example, multiply array a (3 x 3 x 2) by array b (3 x 3):

a <- array(1:18, dim=c(3,3,2))
b <- diag(3)

下失败,因为数组非顺应性。

The following fails because the arrays are non-conformable.

> a * b

有关它的工作,你必须投阵列 B 到一个数组与正确的
维数。

For it to work, you have to cast array b into an array with the correct number of dimensions.

> a * array(b, dim=c(3,3,2))

这并不在我看来他们是非常简单,我敢肯定有一定
是一个简单的方法。

This doesn't strike me as being very straightforward and I'm sure there must be a simpler way.

推荐答案

您可以试试:

a * c(b)

C 将去除属性,那么这将使回收b 作为一个简单的载体,导致我相信是你想要的结果:

c will strip attributes, which will then allow recycling of b as a simple vector and lead to what I believe is your desired outcome:

, , 1

     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    5    0
[3,]    0    0    9

, , 2

     [,1] [,2] [,3]
[1,]   10    0    0
[2,]    0   14    0
[3,]    0    0   18

这篇关于如何处理&QUOT;非顺应性&QUOT;数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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