[英]Debugging the error "Dimensions of arrays being concatenated are not consistent" in MATLAB
I have a function VanderPol()
which is supposed to give a vector output, but it doesn't seem to work.我有一个函数
VanderPol()
应该提供矢量输出,但它似乎不起作用。 It is just three lines of code but I cannot seem to find the bug.它只有三行代码,但我似乎无法找到错误。
The function is功能是
function [output] = VanderPol(y, i)
output = [y(2,i); (1-y(1,i)^2)*y(2,i) -y(1,i)];
end
and it is called as它被称为
z = [1 2 3;
4 5 6];
VanderPol(z,1)
I recieve an error message stating that VanderPol(z,1)
is faulty, but no hint why.我收到一条错误消息,指出
VanderPol(z,1)
有问题,但没有提示原因。 The exact error message is shown below.确切的错误消息如下所示。 Can anyone spot the bug?
任何人都可以发现错误吗?
Error using vertcat
Dimensions of arrays being concatenated are not consistent.
This is a bit of an edge case: You can construct arrays in MATLAB by separating elements either by a comma ,
or a space 这是一个位的边缘壳体的:可以通过分离的元件或者通过逗号构建MATLAB阵列
,
或一个空间 .
。 Thus, the following ways both work and give the same result:
因此,以下方式都可以工作并给出相同的结果:
a = [1, 2, 3]
b = [1 2 3]
When building matrices, this works similarly, and rows are separated by a semicolon or a new line, ie we have the following equivalent possibilities: 在构建矩阵时,其工作原理类似,并且行之间用分号或换行分隔,即,我们具有以下等效的可能性:
A = [1, 2, 3; 4, 5, 6]
B = [1 2 3; 4 5 6]
C = [1, 2, 3
4, 5, 6]
D = [1 2 3
4 5 6]
Now to your example: your array is the following: 现在来看您的示例:数组如下:
[y(2,i); (1-y(1,i)^2)*y(2,i) -y(1,i)]
The first row contains one element y(2,i)
. 第一行包含一个元素
y(2,i)
。 The second row, however, is interpreted as two elements: (1-y(1,i)^2)*y(2,i)
and -y(1,i)
, due to the space between these parts. 但是,由于这两部分之间的空间,第二行被解释为两个元素:
(1-y(1,i)^2)*y(2,i)
和-y(1,i)
。 Ie MATLAB thinks you are using a space to separate two parts of an array like in b
above. 即MATLAB认为您正在使用空格来分隔数组的两个部分,如上面的
b
所示。 It interprets the input like the following: 它将输入解释如下:
[y(2,i); (1-y(1,i)^2)*y(2,i), -y(1,i)]
If you paste the code into MATLAB, you will thus get an error complaining that it is not possible to have an array with 1 element in the first and 2 elements in the second row: 如果将代码粘贴到MATLAB中,则会收到一个错误消息,提示不可能有一个数组,数组的第一行有1个元素,第二行有2个元素:
>> [y(2,i); (1-y(1,i)^2)*y(2,i) -y(1,i)]
Error using vertcat
Dimensions of arrays being concatenated are not consistent.
To solve the problem you have to tell MATLAB that there is only one element in the second row, given by the subtraction (1-y(1,i)^2)*y(2,i) -y(1,i)
. 要解决该问题,您必须告诉MATLAB第二行中只有一个元素,由减法
(1-y(1,i)^2)*y(2,i) -y(1,i)
。 Here are some ways to do that: 以下是一些方法:
output = [y(2,i); (1-y(1,i)^2)*y(2,i) - y(1,i)]; % spaces on both sides of -
output = [y(2,i); (1-y(1,i)^2)*y(2,i)-y(1,i)]; % no spaces around -
output = [y(2,i); ((1-y(1,i)^2)*y(2,i) -y(1,i))]; % parentheses around everything
SEI UN GRANDE MI HAI SVOLTATO LA SERATA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.