Matlab错误:???下标索引必须是实正整数或逻辑数

Matlab错误:???下标索引必须是实正整数或逻辑数,matlab,function,Matlab,Function,我自己写的函数有问题。我没有发现任何问题如何解决自己,所以我把它张贴在这里,希望有人会看到我没有看到的。。。(这是我的第一个问题,我不知道如何在Matlab代码中格式化,对此我很抱歉) 这是我的函数,它计算光线(由CD段给出)在“墙”(由AB给出)上的入射角。AB(墙)应为水平或垂直,CD段和墙AB应具有交点: function angle = incidentAngle(AB,CD) %AB and CD are two vectors of size 1x4 %AB = [a1 a2 b1

我自己写的函数有问题。我没有发现任何问题如何解决自己,所以我把它张贴在这里,希望有人会看到我没有看到的。。。(这是我的第一个问题,我不知道如何在Matlab代码中格式化,对此我很抱歉)

这是我的函数,它计算光线(由CD段给出)在“墙”(由AB给出)上的入射角。AB(墙)应为水平或垂直,CD段和墙AB应具有交点:

function angle = incidentAngle(AB,CD)

%AB and CD are two vectors of size 1x4
%AB = [a1 a2 b1 b2] et CD = [c1 c2 d1 d2]
%AB is a segment from the point (a1,b1) to the point (a2,b2)


    if(AB(1)==AB(3)) % The wall is vertical
        if(CD(1)==CD(3)) % The "ray" is vertical too, the angle is 90° or pi/2
            angle = pi/2;
        else
            angle = abs(atan((CD(2)-CD(4))/(CD(1)-CD(3))));
        end
    else
        if(AB(2)==AB(4))% The wall is horizontal
            if(CD(2)==CD(4)) % The "ray" is horizontal too, the angle is 90° or pi/2
                angle = pi/2;
            else
                angle = abs(atan((CD(1)-CD(3))/(CD(2)-CD(4))));
            end
        end
    end

end
例如,问题在于:

当我将AB和CD定义为

AB = [0 1 0 5];
CD = [-1 2 3 4];
我也这么认为

angle = incidentAngle(AB,CD)
在命令窗口中,我收到消息错误:

??? Subscript indices must either be real positive integers or logicals.
我不明白为什么

如果现在我只是复制命令窗口中的函数,如下所示:

AB = [0 1 0 5];
CD = [-1 2 3 4];

angle = 0;

if(AB(1)==AB(3)) % The wall is vertical
    if(CD(1)==CD(3)) % The "ray" is vertical too, the angle is 90° or pi/2
        angle = pi/2;
    else
        angle = abs(atan((CD(2)-CD(4))/(CD(1)-CD(3))));
    end
else
    if(AB(2)==AB(4))% The wall is horizontal
        if(CD(2)==CD(4)) % The "ray" is horizontal too, the angle is 90° or pi/2
            angle = pi/2;
        else
            angle = abs(atan((CD(1)-CD(3))/(CD(2)-CD(4))));
        end
    end
end

angle
我得到了正确的答案

angle =

0.4636

有一个内置的Matlab函数叫做
angle
,用变量名覆盖它会带来麻烦。尝试更改该变量名,改用名称
angl
。这应该能解决你的问题

我在我的工作区中创建了一个新函数,并尝试使用您的输入重新创建您的错误,它对我来说运行良好。不太清楚问题是什么。我使用的是R2012b BTWW,我不明白为什么它工作正常,但当我调用函数时却不行。。。该函数(我认为)编写得很好,并保存在正确的文件夹中,尽管它只是不运行…也请参见。@mwua您是否也更改了函数的名称?当我使用
function angle=incidentAngle(AB,CD)时,它对我有效
并将所有
角度
变量引用更改为
角度
当我将所有“角度”更改为“角度”时,它不起作用。。。但当我将函数名改为“incidentagl”时,它起了作用。谢谢最后一件事,你如何在你的评论中突出显示一个像“function angl=Incidentalge(AB,CD)”这样的词(这是一个正确的词吗?我是比利时人,不知道正确的词…无论如何)在你想要突出显示的词之前和之后使用`符号'。