MATLAB Answers

I keep getting the error index exceeds the number of array elements(1)

128 views (last 30 days)
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
Brian Peoples
Brian Peoples on 2 Feb 2019
I editted the code and it seems I am able to get a 1 or a 0 for each roll of an 11 or a 12 by using a logical. I was wondering how I would get a percentage of each true logical (aka each free food item) out of 300.
My new code is:
roll = zeros(1,300);
for i = 1:300
roll = zeros(i);
dice = 1 + ceil(11*rand(i));
freeornah = roll(i)+dice(i);
free = logical(freeornah(freeornah>10))
%percent = free(i)/300 (here is where i'm getting stuck!!)
end

Sign in to comment.

Accepted Answer

Satoshi Kobayashi
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;

More Answers (1)

Dhruvi Upendra
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
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.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!