简体   繁体   中英

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. 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. 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 . 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) . 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. Ie MATLAB thinks you are using a space to separate two parts of an array like in b above. 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:

>> [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) . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM