For loop dies in the middle of solving

So the function works until a point in the for loop. I debugged and figured out the exact spot is in the for loop when i=.6 if you step until the line that says" u(:,i)=uvnp1(1:2,1)" the function basically gives up. And it gives me this error message "??? Subscript indices must either be real positive integers or logicals." It doesnt make sense to me because the i IS a real positive integer. Here is the function run it using the given numbers and you will see what I am talking about
function oscillation(M,C,delta_t,tf,u0,v0)
% M is the masses matrix
% C is the spring constants matrix
% delta_t is the time step
% tf is the total time
% u0 is the initial positions
% v0 is the initial velocities
A=[1 0;-1 1];
K=A'*C*A;
GT1=eye(4);
GT1(3:4,1:2)=-delta_t*eye(2)/2;
GT1(1:2,3:4)=((delta_t)*(M\K))/2;
GT2=eye(4);
GT2(3:4,1:2)=delta_t*eye(2)/2;
GT2(1:2,3:4)=-((delta_t)*(M\K))/2;
GT=GT1\GT2;
time=0:delta_t:tf;
u=zeros(2,(tf/delta_t)+1);
v=zeros(2,(tf/delta_t)+1);
u(:,1)=u0;
v(:,1)=v0;
uvn=[u0;v0];
for i=(delta_t:delta_t:tf)
uvnp1=GT*uvn;
u(:,(i/delta_t)+1)=uvnp1(1:2,1)
v(:,(i/delta_t)+1)=uvnp1(3:4,1)
uvn=uvnp1;
end
end
% oscillation([2 0;0 1],[1 0;0 2],0.1,1,[0;0],[1;-1])

 Accepted Answer

Image Analyst
Image Analyst on 18 Feb 2013
Edited: Image Analyst on 18 Feb 2013
Since when is 0.6 an integer? Try this. I don't know if it's right, but at least it produces the arrays without crashing:
function test()
oscillation([2 0;0 1],[1 0;0 2],0.1,1,[0;0],[1;-1])
end
function oscillation(M,C,delta_t,tf,u0,v0)
% M is the masses matrix
% C is the spring constants matrix
% delta_t is the time step
% tf is the total time
% u0 is the initial positions
% v0 is the initial velocities
A=[1 0;-1 1];
K=A'*C*A;
GT1=eye(4);
GT1(3:4,1:2)=-delta_t*eye(2)/2;
GT1(1:2,3:4)=((delta_t)*(M\K))/2;
GT2=eye(4);
GT2(3:4,1:2)=delta_t*eye(2)/2;
GT2(1:2,3:4)=-((delta_t)*(M\K))/2;
GT=GT1\GT2;
time=0:delta_t:tf;
u=zeros(2,(tf/delta_t)+1);
v=zeros(2,(tf/delta_t)+1);
u(:,1)=u0;
v(:,1)=v0;
uvn=[u0;v0];
counter = 1;
for i=(delta_t:delta_t:tf)
uvnp1=GT*uvn;
u(:,counter)=uvnp1(1:2,1)
v(:,counter)=uvnp1(3:4,1)
uvn=uvnp1;
counter = counter + 1;
end
end

2 Comments

Well the i=0.6 was divided by delta_t=0.1 which made it six. But this solved my problem, thanks.

Sign in to comment.

More Answers (1)

The problem can be caused by
u(:,(i/delta_t)+1)
Are you sur that i/delta_t is real positive integer or logical

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!