index must be positive integer or logical
2 views (last 30 days)
Show older comments
I am using an explicit/implicit scheme for Gravity waves in one dimension and I'm using the following code.
ntot = 100;
jmax = 100;
j = 50;
h=10; dx = 1000; dt = 0.5;
a = (dt*h)/dx;
for j = 1:((n+1)) %Initial conditions
U(:,1)=0;
U(jmax/2,1) =100;
end
for n=1:ntot+1 %Boundary conditions
U(1,n) = 1;
U(n+1,n) = 0;
end
for n = 1:ntot;
for j = 1:jmax-1;
N(j,n+1) = N(j,n)-a*(U(j+1/2,n)-U(j-1/2,n));
U(j+1/2,n) =U(j+1/2,n+1) - B*(N(j,n+1)-N(j+1,n+1));
end
end
hold on
plot(N(:,n+1));
plot (U(:,n));
However, when running it, an error "Attempted to access U(1.5,1); index must be a positive integer or logical." is being displayed. I understand why it is displaying such error (because j is located in the middle of each cell i.e. j is found at 0.5, 1.5, 2.5 etc...and matlab does not read such index. Is there a way how I can solve this problem please. Thanks
1 Comment
Jan
on 31 Mar 2016
Please use the "{} Code" button to format your code. Currently it is hard to read.
Answers (3)
KSSV
on 31 Mar 2016
If you have a array/ matrix, the indices (i,j) must be integers. They cannot be fractions, zeros or negatives. You are accessing U(1.5,1). It is not allowed.
Jan
on 31 Mar 2016
The intention of your code is not clear. E.g. this is meaningless:
for j = 1:((n+1)) %Initial conditions
U(:,1) = 0;
U(jmax/2,1) = 100;
end
The body of the loop does not depend on the loop counter j, such that you set the the elements n times to the same value. Why?
It is hard to suggest how to solve the problem of the non-integer indices, because the code does not contain any comments which explain the purpose. All we see is a failing code, so how could we fix it? Perhaps you should simply multiply all indices by 2. Or you could replace U(1.5) by (U(1)+U(2))/2, if this satisfies your needs.
2 Comments
Torsten
on 31 Mar 2016
I don't understand your problem.
Just save the values you would have stored in U(j+1/2,n) now in U(j+1,n) (i.e. shift the j-index by 1/2 to the right).
Best wishes
Torsten.
Image Analyst
on 31 Mar 2016
There is a FAQ on that that explains it pretty well: http://matlab.wikia.com/wiki/FAQ#How_do_I_fix_the_error_.22Subscript_indices_must_either_be_real_positive_integers_or_logicals..22.3F
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!