MATLAB: Error: Index exceeds matrix dimensions

matlab function

The data describes a smooth general curve that then juts up in the middle, and then comes back down and continues the first curve. This function attempts to find the area under the abnormal curve in the middle. Matlab says there is an error in this line: Area=Area+((((func(y)-specdata(y))+(func(z)-specdata(z)))/2)*(z-y));
Thanks in advance
function [ Area ] = Area( func, freq, specdata)
%UNTITLED2 Uses the input function as well as the input data to find the
%area under the spectral lines. This is done using many small trapezoids in
%between each consecutive set of points, finding the values according to the
%function and using the data. The area function is ((a+b)/2)*h.
Area=0;
j=1;
r=length(freq);
while j<r
y=freq(j);
z=freq(j+1);
Area=Area+((((func(y)-specdata(y))+(func(z)-specdata(z)))/2)*(z-y));
j=j+1;
end
end

Best Answer

Before you do anything else and before I would even consider whether there are other problems in the code, you cannot name a variable the same as a function. In normal Matlab usage this is bad, but to name a variable the same as the function whose workspace that variable is in is surely catastrophic.
I've never tried doing it to know exactly what takes precedence where, but just make sure you never do it then you don't need to know exactly what happens!
There may well be other problems with that line too.
The simplest way to find those yourself is to break the line down into smaller components between each operator and then you can see what size each component is. This way you quickly see if your code is trying to add together two arrays of different dimension or se which part of the line is causing an indexing error.