如何将数组数组转换为矩阵? [英] How to convert an array of array into a matrix?

查看:36
本文介绍了如何将数组数组转换为矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想将向量值函数 phi 应用于向量 x:

Suppose I want to apply a vector-valued function phi to a vector x:

phi(x, d) = [x.^i for i=0:d]    # vector-valued function
x = rand(7)                     # vector
y = phi(x, 3)                   # should be matrix, but isn't

现在 y 应该是一个矩阵,但它是一个 4-element Array{Array{Float64,1},1},即一个数组数组.实际上,我希望 y 是一个矩阵.phi 的实现是否错误?或者如何转换?

Now y should be a matrix, but it is an 4-element Array{Array{Float64,1},1}, i.e. an array of arrays. Actually, I want y to be a matrix. Is the implementation of phi wrong? Or how do I convert it?

谢谢!

推荐答案

如您所述,您可以使用 hcat(x...) 连接数组数组 x>,但通常最好先创建一个矩阵.在这种情况下,您可以通过两种方式做到这一点:

As you noted, you can concatenate an array of arrays x using hcat(x...), but it's usually better to create a matrix to begin with instead. Two ways that you can do it in this case:

  1. 使用广播:

  1. Using broadcasting:

phi(x, d) = x.^((0:d)')

只要x是一个向量,它就会针对行矩阵(0:d)'进行广播.

As long as x is a vector, it will broadcast against the row matrix (0:d)'.

您可以通过转置x而不是范围0:d来获得转置结果.

You can get the transpose result by transposing x instead of the range 0:d.

使用二维数组推导:

phi(x, d) = [xi.^di for xi in x, di in 0:d]

只要 x 是可迭代的,这将起作用.如果 x 是一个 n-d 数组,它将被解释为好像它首先被展平.

This will work as long as x is iterable. If x is an n-d array, it will be interpreted as if it were flattened first.

您可以通过切换理解变量的顺序来转置结果:

You can transpose the result by switching the order of the comprehension variables:

phi(x, d) = [xi.^di for di in 0:d, xi in x]

这篇关于如何将数组数组转换为矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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