I keep getting the error index exceeds the number of array elements(1)
1 view (last 30 days)
Show older comments
Brian Peoples
on 2 Feb 2019
Commented: Walter Roberson
on 2 Dec 2019
roll = zeros(1,300);
for i = 1:300
dice = 1 + ceil(11*rand(1));
end
freeornah = roll+dice(i)
freeornah = roll+dice(i)I keep getting the error index exceeds the number of array elements(1). I am trying to add each number in the column vector roll with each dice roll. Then I'm trying to create a logical where if the number I receive for freeornah is true if it is either 11 or 12.
2 Comments
Stephen23
on 2 Feb 2019
Edited: Stephen23
on 2 Feb 2019
"freeornah = roll+dice(i)I keep getting the error index exceeds the number of array elements(1)."
The reason for that is simple: your completely overwrite dice on every loop iteration, so at the end you have only the scalar value from the final iteration. Then you try to access the 300th element of a scalar array -> error!
"I am trying to add each number in the column vector roll with each dice roll."
Given that roll consists only of zeros then you can ignore it and just add the numbers in dice. Note that roll is not a column vector, it is a row vector. From your description and buggy code it is not very clear what you are trying to achieve. Perhaps a simple example would help, with example input and output arrays.
"Then I'm trying to create a logical where if the number I receive for freeornah is true if it is either 11 or 12."
Use > or ==
Accepted Answer
Satoshi Kobayashi
on 2 Feb 2019
The problem is that dice is completely changed in each loop.
In this case, roll is meaningless.
dice = zeros(1,300);
for i = 1:300
dice(i) = 1 + ceil(11*rand(1));
end
freeornah = dice==11|dice==12;
0 Comments
More Answers (1)
Dhruvi Upendra
on 2 Dec 2019
Edited: Walter Roberson
on 2 Dec 2019
clc clear all
f=@(x,y,z) z; g=@(x,y,z) (x^2+6*x-9)/75; fex=@(x) (12*x^3-54*x^2-x^4)/900;
a=0; b=3; h=0.1; n=30;
y=0; z=0; i=0; for x=a:h:b i=i+1;
k1=f(x,y(i),z(i));
l1=g(x,y(i),z(i));
k2=f(x+0.5*h,y(i)+0.5*k1,z(i)+0.5*l1);
l2=g(x+0.5*h,y(i)+0.5*k1,z(i)+0.5*l1);
k3=f(x+0.5*h,y(i)+0.5*k2,z(i)+0.5*l2);
l3=g(x+0.5*h,y(i)+0.5*k2,z(i));
k4=f(x+h,y(i)+k3,z(i)+l3);
l4=g(x+h,y(i)+k3,z(i)+l3);
y(i+1)=y(i)+(k1+2*k2+2*k3+k4)*h/6;
FF(i)=fex(x);
xx(i)=x;
end
plot(xx,y(1:n+1),'o',xx,FF)
legend('RK4','Exact solution')
grid on
xlabel('X')
ylabel('Y')
title('RK4 vs Exact solution')
I have written Matlab code for Runge Kutta fourth order method for second order differential but I'm getting this error I don't know how to solve it !
1 Comment
Walter Roberson
on 2 Dec 2019
This is unrelated to the user's Question and should be created as its own Question, with a clear indication of what the error message is and which line it is occuring on.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!