Error saying matrices are not the same size

9 次查看(过去 30 天)
I am trying to perform Euler's method for a system of ODE's but when I run the function I keep getting this error "Unable to perform assignment because the size of the left side is 11-by-1 and the size of the right side is 11-by-2", or something like it depending on where I put the colons on the first w in the for loop. I
f=@(t,w) [t*w(2),w(1)*w(2)-t*w(1)];
function [t,w] = eulerSys(f,range,iv,h);
% input f is a vector valued function containing the system of differential equations
% f takes t and w as inputs, where w is an array containing the dependent variables
% the output f should be organized as a row vector
% input range is a vector of length 2 containing an initial time and a final time
% input iv is a vector containing the initial conditions for each dep variable
% input h is a scalar step size
% output t is a column vector containing the times at which we have solution approximations
% output w is a matrix whose columns are the approximations of the different dep variables
%set up an evenly spaced array for t
t = (range(1):h:range(2))';
% Preallocate the solution matrix w. Use the length of t to determine the number of time steps
% and the length of iv to determine the number of functions/ODEs.
% Make sure the matrix is tall, not wide. That is, each column of w should represent one function.
w=zeros(2,length(t))';
w(1,1)=iv(1);
w(1,2)=iv(2);
%input the initial conditions into the first row of w
w
%run through Euler's method to fill in the remaining rows of w
for i = 2:length(t)-1;
w(:,2) = w(:,i)+h*f(t,w(:,i))
end
This is the code that I have for the function, and when I run the function it creates a [11x2] matrix for w, but then for some reason when it runs the for loop it just completely messes it up and changes it to a [11x1] matrix. If I change where the colons are in the foor loop it will either give me a similar error or it just won't work at all.

采纳的回答

KSSV
KSSV 2022-4-28
编辑:KSSV 2022-4-28
I think the loop should be something like this:
for i = 2:length(t)-1;
w(i,:) = w(i-1,:)+h*f(t(i),w(i-1,:)) ;
end
In your code, now your input is complete t. which is a vector and the output will be a vector which you don't want. You need to send the time value at that loop. Also you messed up the indexing in w.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by