用于计算列向量的点积的脚本

时间:2018-04-17 00:03:55

标签: matlab

这是我的代码。它不断给出索引超出矩阵维度的错误。

function [y_out] = my_dot(x,y)
    %for finding the inner product or dot product of two arrays
    %first need to know the size

    [m_x,n_x] = size(x);
    [m_y,n_y] = size(y);
    %ensure is row or column vectors of equal length
    if(m_x ~= 1 && n_x ~=1) || (n_y ~= 1 && n_y ~= 1)
        y_out = 'Failed';
        return
    end

    %determine if x and y are column or row vectors
    %both should be column vectors
    if (m_x == 1 || m_y ==1) %they are row vectors
        y_out = 'Failed';
        return
    end

    %make sure x and y are the same size
    if n_x ~= n_y
         y_out = 'Failed';
         return
    end

    %now do the dot product
    for i = 1:m_x
        y = sum(x(i,1) * y(i,1));
        y_out = y;
    end
end

这就是我得到的

    >> my_dot([1;1],[2;3])
    Index exceeds matrix dimensions.

    Error in my_dot (line 26)

2 个答案:

答案 0 :(得分:2)

MATLAB内置了非常好的实现:

A=rand([42,1]);
B=rand([1,42]);
C=dot(A,B);

答案 1 :(得分:1)

写作时

y = sum(x(i,1) * y(i,1));

您正在将y更改为标量。您索引y(2,1)的下一个循环迭代,现在已超出范围。

循环中需要一个新变量:

y_out = 0;
for i = 1:m_x
    y_out = y_out + x(i,1) * y(i,1);
end

但你也可以通过一次乘法来计算:

y_out = x.' * y;

您的代码中还有一些其他错误。例如,您确保n_x == n_y,但m_xm_y必须相同。

要报告错误情况,请使用error功能。接收实际错误比返回值与用户期望值不匹配更有用。