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

27 ビュー (過去 30 日間)
I need to update t and dx as shown below, but i keep getting the error: "unable to perform assignment because the left and right sides have a different number of elements."
I do understand that t(1) is 1 by 1 , while the new result 2 by 1.
What is the best way of going about this ?
This is the euler approach to analytical solution of ode.
clc;
clear all;
close all;
h = 0.1;
t = 0:h:5;
y = zeros(size(t));
t(1) = -2; % initial conditions
dx(1) =3; %Issue here
n = numel(y);
y_dot = @(t,dx)[dx; -3*dx-7*t];
for i=1:n-1
t(i+1)=t(i)+h;
dx(i+1) = dx(i)+h*y_dot(t(i+1),dx(i)); % Issue here. I tried (1) indexing but wouldn't work.
dx(i+1) = dx(i) + h*y_dot(t(i+1),dx(i+1));
end
  2 件のコメント
Jyotsna Talluri
Jyotsna Talluri 2019 年 12 月 4 日
Can you mention what you want to achieve mathematically?
darova
darova 2019 年 12 月 5 日
y_dot returns 2 values
y_dot = @(t,dx)[dx; -3*dx-7*t];
And you are trying to pass 2 values to dx(i+1)
dx(i+1) = dx(i)+h*y_dot(t(i+1),dx(i));

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

採用された回答

Luna
Luna 2019 年 12 月 4 日
編集済み: Luna 2019 年 12 月 4 日
Hi,
It is because you defined dx = 3 as 1x1 double. Your function y_dot gives 2x1 double as result. So it is not possible to concatanate them because first element is 1x1 and second, third other elements are 2x1. Maybe you can try code I fixed below. Your result dx will be 2x50 matrix at the end of the loop.
If you explain what you need as a result it would be much more better.
h = 0.1;
t = 0:h:5;
y = zeros(size(t));
t(1) = -2; % initial conditions
dx(:,1) =[3;3]; %Changed this 2x1 double array with 3.
n = numel(y);
y_dot = @(t,dx)[dx; -3*dx-7*t];
for i=1:n-1
t(i+1)=t(i)+h;
dx(:,i+1) = dx(i)+h*y_dot(t(i+1),dx(i)); % Changed this with (:,i+1) means all rows of i+1.th column.
dx(:,i+1) = dx(i) + h*y_dot(t(i+1),dx(i+1));
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by