Fixing Array Index Expression
조회 수: 1 (최근 30일)
이전 댓글 표시
I am trying to solve a PDE numerically. I want to save the solution every second, which with a time step of k means I want to save it every 1/k iterations. However, in my code I have:
solution = zeros(t_final+1,N+1);
for i = 1:M
for j = 0:N
% Code that updates the solution is here
end
uold = unew;
if mod(i,1/k) == 0
solution(i*k,:) = unew;
end
end
and this works for updating the second row but then fails and gives the error "Index in position 1 is invalid. Array indices must be positive integers or logical values." I don't understand this though. Doesn't the if statement above preclude any instance where i*k isn't an integer? Does anyone know what the problem is? Since k is explicitly chosen, I can simply replace 1/k with the actual number for a given k and this works. But then every time I change the value of k I have to make sure I change that line as well and I want to avoid doing that if possible.
Just for clarification of what's going on in the interior for loop: I am using two vectors uold and unew to represent the solution to the equation at time steps n and n+1. Basically, I use values from uold to solve for unew and then just keep repeating up until my final time. The variable unew is a 1xN+1 vector that is then stored inside solution when we are at a integer value in time. Each row of solution then represents the solution at a given second -- i.e. row 1 would correspond to the IC preloaded prior to the code shown above, row 2 would correspond to the solution at t=1, row 3 would correspond to the solution at t=2, ..., row t_final+1 would correspond to the solution at t=t_final.
Also, t_final is a variable I set at the top and is always set to be an integer so there aren't any issues there
댓글 수: 1
Rik
2022년 1월 4일
I suspect a floating point error. You should try checking if i*k is integer, instead of checking if the modulo of the inverse is 0.
Mathematically those two are the same, but you're working with numbers here, not symbolic variables.
답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Eigenvalue Problems에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!