0

I am trying to find the minimum value of a function of two variables, and then find the value of the variables.

My method is to iterate the function through several values of the variables and then use the min function to find the lowest value.

minval = -10;
maxval = 10;
n = 1;

for x = minval:maxval
    for y = minval:maxval
        f(n) = abs(x-1)+abs(y-1)+abs(x-3)+abs(y-5)+abs(x-8)+abs(y-3);
        n=n+1;
    end
end
f(n) = abs(x-1)+abs(y-1)+abs(x-3)+abs(y-5)+abs(x-8)+abs(y-3);
fmin = min(f)

The problem is with the last line:

fmin = min(f)

I am getting the error

??? Index exceeds matrix dimensions.

Error in ==> Lab2 at 65
fmin = min(f)

Why is this? Any help is greatly appreciated.

photon
  • 606
  • 4
  • 14
  • 31

3 Answers3

6

Don't define a variable named min. Try this:

which min

What does it tell you?

Note that functions in MATLAB can be overloaded by creating variables with the same name. When you do so, you prevent the function from being accessed by MATLAB. This is RARELY a good idea, so don't do it. The solution is

clear min

So you will delete that variable you have created. Of course, if there was something important in that variable, stuff it somewhere else first.

1

This code runs perfectly when I plug it into my version of Matlab.

If the error is occuring on line 65, then there must be something else going on in your program. Try and turn this part of your program into a function, so that it won't be impacted by everything else that you're working on.

tjr226
  • 605
  • 1
  • 5
  • 15
1

It does indeed look like you have declared a variable called min and so Matlab now treats it like a variable and not a function so it thinks you are trying to index the variable min with the vector f.

But just a comment on your code, leaving off whatever f(442) is you could achieve the same thing in a much more matlabesque fashion without loops like this:

minval = -10;
maxval = 10;

X = minval:maxval;
Y = X;

[xx, yy] = meshgrid(X, Y);
F = abs(xx-1) + abs(yy-1) + abs(xx-3) + abs(yy-5) +abs(xx-8) + abs(yy-3);

Your f is now equivalent to F(:)' (without the final value...), prove it to yourself like this: sum(f(1:end-1) == F(:)')

F as a matrix probably makes more sense than f as a flat vector anyway and you can find the min of F like this: min(F(:))

Dan
  • 45,079
  • 17
  • 88
  • 157
  • I see the : operator makes F vector and F(:)' makes it an array. Is this what it's doing? – photon Sep 12 '12 at 20:28
  • F is a 2 dimensional matrix, F(:) flattens it into a row vector and F(:)' transposes the row vector to a column vector. – Dan Sep 12 '12 at 21:33