Search code examples
arraysmatlaboptimizationcelliteration

use five point stencil to evaluate function with vector inputs and converge to maximum output value


I am familiar with iterative methods on paper, but MATLAB coding is relatively new to me and I cannot seem to find a way to code this.

In code language...

This is essentially what I have:

A = { [1;1]  [2;1]  [3;1]  ... [33;1]
      [1;2]  [2;2]  [3;2]  ... [33;2]
       ...    ...    ...   ...  ....
      [1;29] [2;29] [3;29] ... [33;29] }

... a 29x33 cell array of 2x1 column vectors, which I got from:

[X,Y] = meshgrid([1:33],[1:29])

A = squeeze(num2cell(permute(cat(3,X,Y),[3,1,2]),1))

[ Thanks to members of stackOverflow who helped me do this ]

I have a function that calls each of these column vectors and returns a single value. I want to institute a 2-D 5-point stencil method that evaluates a column vector and its 4 neighbors and finds the maximum value attained through the function out of those 5 column vectors.

i.e. if I was starting from the middle, the points evaluated would be :

1.

A{15,17}(1)
A{15,17}(2)

2.

A{14,17}(1)
A{14,17}(2)

3.

A{15,16}(1)
A{15,16}(2)

4.

A{16,17}(1)
A{16,17}(2)

5.

A{15,18}(1)
A{15,18}(2)

Out of these 5 points, the method would choose the one with the largest returned value from the function, move to that point, and rerun the method. This would continue on until a global maximum is reached. It's basically an iterative optimization method (albeit a primitive one). Note: I don't have access to the optimization toolbox.

Thanks a lot guys.


Solution

  • EDIT: sorry I didn't read the iterative part of your Q properly. Maybe someone else wants to use this as a template for a real answer, I'm too busy to do so now.

    One solution using for loops (there might be a more elegant one):

    overallmax=0;
    for v=2:size(A,1)-1
        for w=2:size(A,2)-1
            % temp is the horizontal part of the "plus" stencil
            temp=A((v-1):(v+1),w); 
            tmpmax=max(cat(1,temp{:})); 
            temp2=A(v,(w-1):(w+1));
            % temp2 is the vertical part of the "plus" stencil
            tmpmax2=max(cat(1,temp2{:})); 
            mxmx=max(tmpmax,tmpmax2);
            if mxmx>overallmax
                overallmax=mxmx;
            end
         end
    end
    

    But if you're just looking for max value, this is equivalent to:

    maxoverall=max(cat(1,A{:}));