Error: Index exceeds matrix dimensions?

1 view (last 30 days)
Mark
Mark on 3 Dec 2014
Commented: Guillaume on 3 Dec 2014
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

Accepted Answer

Adam
Adam on 3 Dec 2014
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.
  5 Comments
Mark
Mark on 3 Dec 2014
Freq and specdata are two vectors with data that was given to us. Theyre exactly the same length, basically like a series of x and y. Like I said, I got it figured out by going into the line. I was incorrect in saying specdata(y), since that told the function to look for a "y value" for an"x value" that didnt exist. Should have been specdata(j)
Guillaume
Guillaume on 3 Dec 2014
And the morale of the story is: use names that represent the purpose of a variable rather than j, r, y, z.
You may now know what these stand for, but in a year's time when you reread your code, you'll have to spend some time understand what they do.

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB 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!