使用简单矩阵乘法时出错

Den*_*din 10 matlab matrix-multiplication

我在简单的乘法中偶然发现了一个错误,让我感到惊讶.这里发生了什么,我一直认为*只是为了矩阵乘法.

x = 2;
y = zeros(1,4);
y(1) = 1 *x;
y(2) = x* 1;
y(3) = (x *1);
y(4) = x *1;
y
x *1
Run Code Online (Sandbox Code Playgroud)

将给出以下输出:

y =

     2     2     2     1

Error: "x" was previously used as a variable,
conflicting with its use here as the name of a function or command.
See MATLAB Programming, "How MATLAB Recognizes Function Calls That Use Command Syntax" for details.
Run Code Online (Sandbox Code Playgroud)

有谁知道这里发生了什么?当然,我证实这x不是一个功能.

nkj*_*kjt 11

这取决于间距.另请参阅此处以获得更长的解释以及何时可能存在真正模糊性的一些示例,但基本上前三个将按预期工作,最后将假设您尝试使用输入*1调用函数x:

x*1  
x * 1 
x* 1
x *1
Run Code Online (Sandbox Code Playgroud)

如果将输出分配给某个变量,则无论间距如何都不会发生这种情况:

y(2) = x *1
z = x *1
x = x *1
Run Code Online (Sandbox Code Playgroud)

  • @DennisJaheruddin也试试这个:"{[1 + 2],[1 + 2],[1 + 2],[1 + 2]}`.这个怪癖是我不喜欢MATLAB的事情之一. (3认同)

Moh*_*nia 9

发生这种情况是因为当你x *1在一个单独的行中时,MATLAB将x一个函数解释为尝试'*1'作为参数传递给它,然后它实现了这x是一个变量,因此错误.