python:将ndy中的两个1d矩阵相乘

时间:2016-04-26 17:19:43

标签: python numpy matrix

a = np.asarray([1,2,3])

b = np.asarray([2,3,4,5])

a.shape

(3,)

b.shape

(4,)

我想要一个3乘4矩阵,它是a和b的乘积

1
2    *    2 3 4 5
3

np.dot(a,b.transpose())

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: objects are not aligned
当数组为2d时,

点积仅相当于矩阵乘法,所以np.dot不起作用。

4 个答案:

答案 0 :(得分:4)

这是np.outer(a, b)

In [2]: np.outer([1, 2, 3], [2, 3, 4, 5])
Out[2]: 
array([[ 2,  3,  4,  5],
       [ 4,  6,  8, 10],
       [ 6,  9, 12, 15]])

答案 1 :(得分:3)

无需使用matrix子类型。常规array可以扩展到2d(如果需要可以转置)。

In [2]: a=np.array([1,2,3]) 
In [3]: b=np.array([2,3,4,5])

In [4]: a[:,None]
Out[4]: 
array([[1],
       [2],
       [3]])

In [5]: a[:,None]*b   # outer product via broadcasting
Out[5]: 
array([[ 2,  3,  4,  5],
       [ 4,  6,  8, 10],
       [ 6,  9, 12, 15]])

制作该列数组的其他方法

In [6]: np.array([[1,2,3]]).T
Out[6]: 
array([[1],
       [2],
       [3]])

In [7]: np.array([[1],[2],[3]])
Out[7]: 
array([[1],
       [2],
       [3]])

In [9]: np.atleast_2d([1,2,3]).T
Out[9]: 
array([[1],
       [2],
       [3]])

答案 2 :(得分:0)

而不是asarray,请使用asmatrix

import numpy as np
a = np.asmatrix([1,2,3])
b = np.asmatrix([2,3,4,5])
a.shape #(1, 3)
b.shape #(1, 4)
np.dot(a.transpose(),b)

结果:

matrix([[ 2,  3,  4,  5],
        [ 4,  6,  8, 10],
        [ 6,  9, 12, 15]])

答案 3 :(得分:0)

下面的代码按照要求进行,基本上你在重塑数组时犯了一个错误,你应该重新整形它们,以确保满足矩阵乘法属性。

public class SBST <Value>
{
    private class Node
    {
        private Node left;
        private Node right;
        private String key;
        private Value value;
        public Node(Node left,Node right, String key, Value value)
        {
            this.left = left;
            this.right = right;
            this.key =  key;
            this.value = value;
        }
    }

private Node root;
private int size;
private String [] keys;
private Value [] values;
private int currentSize;
private Random rand = new Random();

public SBST (int size)
{
    if (size < 0)
    {
        throw new IllegalArgumentException();
    }
    else
    {
        this.size = size;
        this.keys = new String[size];
        this.values = new Value[size];
        this.currentSize = 0;
    }
}

public int height(String keys)
{
    if (keys == null)
    {
        return 0;
    }
    else
    {
        int l = height(keys.left);
        int r = height(keys.right);
        if (l > r )
        {
            return l +1;
        }
        else
        {
            return r + 1;
        }
    }
}