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

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

问题描述

假设我想将向量值函数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天全站免登陆