Fix: Index in position 2 is invalid. Array indices must be positive integers or logical values. ??
12 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I am getting the following error message in full when I run this code.
"Index in position 2 is invalid. Array indices must be positive integers or logical values.
Error in File (line 28)
x(j,i) = x(j, i-1) + delta;"
Can anyone tell me how I can fix the code to avoid gettting this error message and generate the plot? Here's the full code:
%Defining variables
M = 100;
ni = 1;
nf = 151;
for n = (1:1:151)
end
X = zeros(M, n+1);
%Assign 1 step for particles
for j = 1:100
%loop through all time points
for i = 1:n+1
%Random number that is either 0 or 1
random = rand;
%Partition randomly generated numbers in half. If the number is less than 0.5, delta will be equal to -12 while if the number is greater than 0.5, delta will equal 12
if random < 0.5
delta = -12;
elseif random > 0.5
delta = 12;
end
%Assign x position as original x position with the added delta step
x(j,i) = x(j, i-1) + delta;
end
end
%plot x values across all time points
plot(0:n,x)
0 comentarios
Respuesta aceptada
KSSV
el 3 de Feb. de 2021
This line:
x(j,i) = x(j, i-1) + delta;
In the above the value of j-1 will be zero when j = 1. This case, the index will be zero and this is not permitted in MATLAB. The index should be positive integer.
So you have to srat loop with j = 2.
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!