. Advertisement .
..3..
. Advertisement .
..4..
I’m new on Matlab. I’m facing the error ”index exceeds the number of array elements (1)” when I run this line:
P2(i) = (V2(i) - V0) / C2;
The code runs without a hitch on my computer, but when transferred and executed on another, it displays the error message.
Here is my code:
dt = 0.005; N = 200; %(s)
P3s = 2; P3d = 23.5; %(mmHg)
V2(1) = .475; %(L)
V0 = .06; %(L)
C2 = 0.05; %(L/mmHg)
R1 = 30; R2 = 30; %(mmHg*s/L)
P1 = 11; %(mmHg)
P3(1:120) = P3s;
P3(121:200) = P3d;
t = 0:dt:(N-1)*dt;
plot(t, P3)
xlabel('Time (s)'), ylabel('Pressure (mmHg)')
for i = 1:N
P2(i) = (V2(i) - V0) / C2;
if P2(i) > P3(i); Q3(i) = (P2(i) - P3(i)) / R2;
else Q3(i) = 0;
end
Q1(i) = (P1 - P2(i)) / R1;
Q2(i) = Q1(i) - Q3(i);
P2(i+1) = P2(i) + Q2(i)*dt;
end
tp = 0:dt:N*dt;
figure
plot(tp, P2)
xlabel('Time (s)'), ylabel('P2 (mmHg)')
I am looking forward to gaining some knowledge from all experts. Thank you, guys!
The cause: I think this error happens because in your code, you only define V2(1); you do not expand the V2 variable’s size. Therefore, I believe that the code that gives values to V2(i+1) in your for loop is missing. It can run in your computer because another script’s V2 variable with the correct size is in your workspace, which prevents the code from yelling at you.
Solution: You can fix this error by adding a line in your for loop, as the following:
→ Read more: How to Fix The Error “Index Exceeds The Number of Array Elements (1)”? – A Complete Guide