Unable to perform assignment because the left and right sides have a different number of elements.

7 ビュー (過去 30 日間)
I am getting the error code in the title for line 40.
%% Clear MATLAB
clear;
clc;
%% Known Values
h=0.01;
tlim=40;
t=0:h:tlim;
F0=20;
wf=3;
k=5.15;
c=12.2;
P=F0*sin(wf*t);
K=zeros(1,4001);
L=zeros(1,4001);
%% Initial Conditions
x(1)=-0.02;
xdot(1)=0;
y(1)=xdot(1);
%% Define Equations
f1=@(x,y,t) y;
f2=@(x,y,t) (P-k*x-c*xdot);
%% RK4 Loop
for i=1:tlim
t(i+1)=t(i)+h;
K1=h*f1(x(i),y(i),t(i));
L1=h*f2(x(i),y(i),t(i));
K2=h*f1(x(i)+h*K1/2,y(i)+h*K1/2,t(i)+h/2);
L2=h*f2(x(i)+h*L1/2,y(i)+h*L1/2,t(i)+h/2);
K3=h*f1(x(i)+h*K2/2,y(i)+h*K2/2,t(i)+h/2);
L3=h*f2(x(i)+h*L2/2,y(i)+h*L2/2,t(i)+h/2);
K4=h*f1(x(i)+h*K3,y(i)+h*K3,t(i)+h);
L4=h*f1(x(i)+h*L3,y(i)+h*L3,t(i)+h);
K(i+1)=K(i)+(1/6)*(K1+2*K2+2*K3+K4);
L(i+1)=L(i)+(1/6)*(L1+2*L2+2*L3+L4);
end

回答 (2 件)

VBBV
VBBV 2022 年 11 月 27 日
K=zeros(1,4100);
L=zeros(1,4100);
Check the size of vectors K and L
  6 件のコメント
VBBV
VBBV 2022 年 11 月 27 日
As @imageanalyst told, you need to assign to check with x and y vectors inside the for loop
x(i+1) = x(i) + something;
y(i+1) = y(i) + something;
for i = 1:tlim-1 % this too

サインインしてコメントする。


Image Analyst
Image Analyst 2022 年 11 月 27 日
4001 is different than 4100. you might need to do this:
h=0.01;
tlim=40;
t=0:h:tlim;
numElements = numel(t)
F0=20;
wf=3;
k=5.15;
c=12.2;
P=F0*sin(wf*t);
K=zeros(1, numElements);
L=zeros(1, numElements);
but then you just run into trouble later because you're trying to use x(2), etc. in
for i=1: numElements - 1
t(i+1)=t(i)+h;
K1=h*f1(x(i),y(i),t(i));
when there is no second element to x or y. They're scalars.
  2 件のコメント
Image Analyst
Image Analyst 2022 年 11 月 27 日
You need to define x and y in advance of entering your loop. What do you expect or want them to be? I have no idea. If you leave it up to me I'd just assign them as all zeros
x = zeros(1, numElements);
y = zeros(1, numElements);
or maybe random numbers
x = rand(1, numElements);
y = rand(1, numElements);
but you probably woudn't want that

サインインしてコメントする。

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by