Search code examples
vhdlproductxilinx

How to find dot product of two vectors in vhdl?


I am new to VHDL. I am trying to design a generic code for vectors dot or scalar product on Xilinx FPGA. Suppose we have a vector two vectors of

V1=[1,4,5,1] and V2=[3,6,9,1].

We can find it using

V1.V2=(1x3)+(4x6)+(5x9)+(1x1)=73
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.ALL;

entity dot_product is
    Port ( vector_x : in STD_LOGIC_VECTOR (3 downto 0);
           vector_y : in STD_LOGIC_VECTOR (3 downto 0);
           r0 : out STD_LOGIC_VECTOR (3 downto 0);
           r1 : out STD_LOGIC_VECTOR (3 downto 0);
           r2 : out STD_LOGIC_VECTOR (3 downto 0);
           result : out STD_LOGIC_VECTOR (7 downto 0));
end dot_product;

architecture Behavioral of dot_product is

begin
r0 <= std_logic_vector(signed(vector_x(0)* vector_y(0)));
r1 <= std_logic_vector(signed(vector_x(1)* vector_y(1)));
r2 <= std_logic_vector(signed(vector_x(2)* vector_y(2)));
r3 <= std_logic_vector(signed(vector_x(3)* vector_y(3)));
result<=r0+r1+r2+r3;

end Behavioral;

How can we find its dot product in VHDL and later I can change vector size according to my requirement. Please help. Thanks:)


Solution

  • These are some notes:

    • vector_x : in STD_LOGIC_VECTOR (3 downto 0);

    this is not a vector as in math. It is a an array of bits zeros and ones. so you can use it to represent numbers from 0 (0000) to 15 (1111).

    if you want to have a vector, consider declaring an array of std_logic_vector.

    type t_vector is array (integer range <>) of std_logic_vector(3 downto 0);

    consider reading this: https://www.nandland.com/vhdl/examples/example-array-type-vhdl.html

    then you declare your vectors as an array with type t_vector.

    after that, you can use for loop in a process to do the multiplication and addition. consider reading this: http://habeebq.github.io/writing-a-2x2-matrix-multiplier-in-vhdl.html

    to have a generic array size, consider using an unconstrained array or generic for the size.

    entity dot_product is
        generic (width : positive := 8);
        port (vector_x : in t_vector (width downto 0);
              vector_y : in t_vector (width downto 0);
                result : out STD_LOGIC_VECTOR (7 downto 0));
    end dot_product ;