index must be positive integer or logical
이전 댓글 표시
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
Jan
2016년 3월 31일
Please use the "{} Code" button to format your code. Currently it is hard to read.
답변 (3개)
KSSV
2016년 3월 31일
0 개 추천
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
2016년 3월 31일
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.
Image Analyst
2016년 3월 31일
0 개 추천
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
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!