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

1 view (last 30 days)
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

Answers (2)

VBBV
VBBV on 27 Nov 2022
K=zeros(1,4100);
L=zeros(1,4100);
Check the size of vectors K and L
  6 Comments
joe brady
joe brady on 27 Nov 2022
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 on 27 Nov 2022
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

Sign in to comment.


Image Analyst
Image Analyst on 27 Nov 2022
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 Comments
joe brady
joe brady on 27 Nov 2022
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 on 27 Nov 2022
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

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!