index exceeds the number of array elements (1).
3 views (last 30 days)
Show older comments
i have function to check percentage of an error. when i run, i have error message
Index exceeds the number of array elements (1).
Error in tutorial2 (line 10)
fvalue=4/(1 + midx(i)^2);
could you guys help me to solve this problem?
function err = tutorial2(nPoints)
%% Midpoint rule for integral 4/(1 + x^2) from x = 0 to x = 1
% inputs: - nPoints number of points in domain
% outputs: - err percentage error (absolute value)
x=linspace(0,1,nPoints);
dx=x(2)-x(1);
numSol=0;
for i=1:nPoints
midx=(x(i)+x(i+1))/2;
fvalue=4/(1 + midx(i)^2);
numSol=numSol+fvalue;
end
numSol=numSol*dx;
analyticalSol=pi/4;
err=abs((analyticalSol-numSol)*100/numSol);
end
0 Comments
Answers (1)
Geoff Hayes
on 9 Mar 2019
changsu - I think there are a couple of bugs with the above code. When running it, the first error is
Attempted to access midx(2); index out of bounds because numel(midx)=1.
Error in tutorial2 (line 10)
fvalue=4/(1 + midx(i)^2);
this is because of the code
midx=(x(i)+x(i+1))/2;
fvalue=4/(1 + midx(i)^2);
In the first line, you treat midx as a scalar, but in the second line, midx is considered to be an array. If you don't need to store the mid-point from each iteration then just do
midx=(x(i)+x(i+1))/2;
fvalue=4/(1 + midx^2);
Else pre-allocate (pre-size) midx as an array outside of the loop and then update and use as such.
The second error will be with
for i=1:nPoints
midx(i)=(x(i)+x(i+1))/2;
% etc.
end
x is an array with nPoints elements...which is fine except on the last iteration of the for loop when i is equal to nPoints which will cause a problem with x(i+1) and throw a Index exceeds matrix dimensions. To get around this, just change the upper bound on your loop to
x=linspace(0,1,nPoints);
dx=x(2)-x(1);
midx = zeros(nPoints, 1);
numSol=0;
for k=1:nPoints-1
midx(k)=(x(k)+x(k+1))/2;
fvalue=4/(1 + midx(k)^2);
numSol=numSol+fvalue;
end
numSol=numSol*dx;
analyticalSol=pi/4;
err=abs((analyticalSol-numSol)*100/numSol);
Note how I've replaced i with k to avoid confusion with the imaginary number (represented in MATLAB by i or j).
2 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!