Using for loop for midpoint method

조회 수: 6 (최근 30일)
Khang Nguyen
Khang Nguyen 2019년 5월 21일
답변: Hitesh 2025년 4월 7일
Hi guys, this is my code
m = 1000;
f = 75000;
v0 = 0;
h = 0.1;
tspan = [0 10];
c = [50,100,500,1000,2000];
dvdt = cell(1,length(c));
for i = 1:length(c);
dvdt{i} = @(t,v) (f-c{i}*v)/m;
end
t =cell(1,length(c));
v =cell(1,length(c));
for k = 1:length(c)
[t{k},v{k}]=midpoint(dvdt{1,k},tspan,v0,h)
end
Error using midpoint
Too many output arguments.
%% Question
I want to use midpoint to calculate the t and v, and my dvdt is relied on c(constant values run from 50 to 2000). The code works, but t and v are released just only based on c = 50, which means my for loop does not work. Can someone please help !!!
Thanks in advance

답변 (1개)

Hitesh
Hitesh 2025년 4월 7일
Hi Khang,
The error "Too many output arguments" indicates that the "midpoint" function did not return two outputs. You need to initializes time and velocity vectors and applies the midpoint method to solve the differential equation. Kindly refer to the folllowing revised code for better understanding:
function [t, v] = midpoint(dvdt, tspan, v0, h)
% Initialize time and solution vectors
t = tspan(1):h:tspan(2);
v = zeros(size(t));
v(1) = v0;
% Midpoint method loop
for n = 1:(length(t) - 1)
tn = t(n);
vn = v(n);
k1 = h * dvdt(tn, vn);
k2 = h * dvdt(tn + h/2, vn + k1/2);
v(n+1) = vn + k2;
end
end
m = 1000;
f = 75000;
v0 = 0;
h = 0.1;
tspan = [0 10];
c = [50, 100, 500, 1000, 2000];
dvdt = cell(1, length(c));
% Create the differential equations for each value of c
for i = 1:length(c)
dvdt{i} = @(t, v) (f - c(i) * v) / m;
end
t = cell(1, length(c));
v = cell(1, length(c));
% Solve using the midpoint method for each value of c
for k = 1:length(c)
[t{k}, v{k}] = midpoint(dvdt{k}, tspan, v0, h);
end

카테고리

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