How can I implement this algorithm in matlab?

조회 수: 8 (최근 30일)
Mark N
Mark N 2018년 11월 20일
댓글: Rik 2018년 11월 21일
Hi! Would somebody be kind enough to show me how to implement this algorithm as a function to return an array with values of x^n and v^n
Lets just say k=5 m=0.5 x0=1 and v0=0.1 with total run time of T=10
  댓글 수: 4
Mark N
Mark N 2018년 11월 21일
Lets say delta t = 0.1 and the superscripts arent indices, just to count iterations
Mark N
Mark N 2018년 11월 21일
x(1) = x0;
v(1) = v0;
function [v(:,i),x(:,i)] = semi-implicit(k,m,N,T,x0,v0)
for i= 1:N
v(:,i+1)= (v(:,i) - (dt*(k/m)*x(:,i)));
x(:,i+1)= (x(:,i) + (dt*v(:,i+1)));
end
end
This is what i've tried but seems its completely wrong

댓글을 달려면 로그인하십시오.

답변 (1개)

Robert U
Robert U 2018년 11월 21일
Hi Mark N
There are some issues with the your matlab syntax.
function [v,x] = semi_implicit(k,m,dt,T,x0,v0)
% check inputs
validateattributes(k, {'numeric'},{'column'});
validateattributes(m, {'numeric'},{'column'});
validateattributes(dt,{'numeric'},{'column'});
validateattributes(T, {'numeric'},{'scalar','nonnegative'});
validateattributes(x0,{'numeric'},{'column'});
validateattributes(v0,{'numeric'},{'column'});
if ~isscalar(k) || ~isscalar(m) || ~isscalar(dt) || ~isscalar(x0) || ~isscalar(v0)
dLgnths = [length(k);length(m);length(dt);length(x0);length(v0)];
if ~all((dLgnths == max(dLgnths)) | dLgnths == 1)
errout = find(~((dLgnths == max(dLgnths)) | dLgnths == 1));
error('Please, check input #%d for being either scalar or vector of length %d (depending on max. length of given input vectors).',errout(1),max(dLgnths))
end
end
% initialize
x = x0;
v = v0;
for ik= 1:T
v(:,end+1)= v(:,end) - (dt .* (k./m) .* x(:,end));
x(:,end+1)= x(:,end) + (dt .* v(:,end));
end
% copy end values to output (here, by overwriting variables v and x)
v = v(:,end);
x = x(:,end);
end
Kind regards,
Robert
  댓글 수: 1
Rik
Rik 2018년 11월 21일
Nice write-up. I do have one remark: if you know how many elements an array will have, you should generally not allow them to grow dynamically (the exceptions are often cases where you know there are only a handful of iterations and the size calculation is expensive).
% initialize
x=zeros(size(x0,1),T);
x(:,1) = x0;
v=zeros(size(v0,1),T);
v(:,1) = v0;
for ik= 1:T
v(:,ik+1)= v(:,ik) - (dt .* (k./m) .* x(:,ik));
x(:,ik+1)= x(:,ik) + (dt .* v(:,ik));
end

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

태그

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by