Kindly help on "Error using horzcat Dimensions of arrays being concatenated are not consistent"

3 次查看(过去 30 天)
Hi All,
I have an assignment to modify code given by a book. But, somehow the code contain "Error using horzcat Dimensions of arrays being concatenated are not consistent". I have tried to browse, what could be the problem, but still not get the solution. Kindly help the code below.
The error lies in X1(i,:)=[Y' dY' t];
F1=1;
F2=-1;
M1=1;
M2=1.5;
B=0.1;
K=0.2;
Coef_1=[B/M1 -B/M1 -B/M2 B/M2];
Coef_2=[K/M1 -K/M1 -K/M2 K/M2];
Y=[0.1; 0.1];
dY=[0; 0];
dt=0.1;
t=0;
tsim=200;
n=round(tsim-t)/dt;
for i=1:n
X1(i,:)=[Y' dY' t];
ddY=[F1/M1;F2/M2] - Coef_1.*dY - Coef_2.*Y;
dY=dY+dt.*ddY;
Y=Y+dt.*dY;
t=t+dt;
end
figure(1)
plot(X(:,5),X(:,1:2))
xlabel('Time (sec.)')
ylabel('Displacements')
figure(2)
plot(X(:,5),X(:,3:4))
xlabel('Time (sec.)')
ylabel('Velocities')

回答(2 个)

JJ Lamb
JJ Lamb 2021-6-16
when i = 2, the line
X1(i,:)=[Y' dY' t];
is trying to concatenate a matrix that is 4x2 (Y'), 4x2 (dY'), and 1x1 (t). Those sizes don't line up, so it's not going to work.
In order for it to work, all the matrices would need to have 4 rows in this case. Something likely needs to be changed with the formatting of ddY to make the sizes remain consistent.

Hamidun
Hamidun 2021-6-17
Do you mean I have to change formula ddY? I tried to understand the error, but still dont get it
  1 个评论
JJ Lamb
JJ Lamb 2021-6-18
I'm not totally sure what this code is trying to do. But the error is that you cannot combine matrices/arrays that don't have at least one dimension that is the same size. You're trying to combine something that has 4 rows with something that has 1 row and that isn't allowed in MATLAB's syntax.
Again, I don't totally know what the code is trying to do, but you probably have two possible solutions.
1) Resize the t vector so it has the same number of rows as the other vectors
X1(i,:)=[Y' dY' t*ones(4,1)];
2) Make the t vector separate. This one would probably make you need to adjust some more of your
X1(i,:)=[Y' dY']; % what was the 5th column is now gone.
And then you could just make a new time vector. You might have to play around with that one a little depending on how you want things to plot.
time = 0:dt:tsim;

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by