How to get final value from iteration rather than block of numbers
6 次查看(过去 30 天)
显示 更早的评论
Hi, Ive written code for Eulers method for an equation of motion for an academic assignment, and I need to return values for z (position) , v (derivative of z) and my student number, using a function with the inputs shown below.
this is the code i have so far:
function [z,v,studentid] = particle(m,g,k,p,V,h,N)
%Numerical Solution
%This function will integrate the equation of motion using the
%forward Euler time stepping method.
% Input params needed from task 1
for studentid=690022044;
g=9.4000;
k=0.1000;
p=1.2000;
m=5;
% Initial conditions and setup
h = 0.1; % step size
t = 0:h:10; % the range of t
z = zeros(size(t)); % allocate the result z
z(1) = 1; % the initial z value
N = numel(z); % the number of z values
% The loop
for i=1:N-1
v=diff(z);
v(i+1) = v(i) + h*(((-g-k*(abs(v(i)).^p)*v(i)/m)));
z(i+1) = z(i)+h*v(i+1);
end
end
%testing
plot(t,v)
xlim([0 9.8])
end
I run it and it works, but it gives me the columns of values as it iterates and doesnt give me z, v and my student number.
Any help would be really appreciated, thanks :)
Holly
0 个评论
采纳的回答
David Hill
2019-11-23
function [z,v,studentid] = particle(m,g,k,p,h)%V and N were not needed as inputs to your function
studentid='690022044';
t = 0:h:10;
z = zeros(size(t));
z(1) = 1;
N = numel(z);
for i=1:N-1
v=diff(z);
v(i+1) = v(i) + h*(((-g-k*(abs(v(i)).^p)*v(i)/m)));
z(i+1) = z(i)+h*v(i+1);
end
end
Once your run your function,
[z,v,studentid]=particle(5,9.4,.1,1.2,.1);
You can display the final values of z, v, and studentid by typing:
disp(z(end));
disp(v(end));
disp(studentid);
Or if all you want is the final values, then:
function [z,v,studentid] = particle(m,g,k,p,h)%V and N were not needed as inputs to your function
studentid='690022044';
t = 0:h:10;
z = zeros(size(t));
z(1) = 1;
N = numel(z);
for i=1:N-1
v=diff(z);
v(i+1) = v(i) + h*(((-g-k*(abs(v(i)).^p)*v(i)/m)));
z(i+1) = z(i)+h*v(i+1);
end
z=z(end);%add these
v=v(end);
end
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!