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

조회 수: 1 (최근 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
joe brady
joe brady 2022년 11월 27일
I'm still getting an error message saying "Arrays have incompatible sizes for this operation.", i notice when i make the suggested K and L changes the matricies is a 2x4100, whereas my values for L1,2,3,4 K1,2,3,4 are in the form 1x4001?
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
joe brady
joe brady 2022년 11월 27일
Thanks for the response, for context x is the displacement of an object at time intervals of h up to tlim, and y is the velocity, how would i transform my code?
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by