Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert f(x,y) to a 2-D matrix (i.e. lookup table)?

Given f = @(x,y) [something with a scalar result], what's the best way that I can compute a lookup matrix A such that A(x,y) == f(x,y) for any x,y within a particular range and domain?

Let's say a function called lookupTable(f,range,domain) did what I want. Then lookupTable(@(x,y) x * y, 12, 12) would yield a matrix containing the multiplication table from 1*1=1 to 12*12=144.

Or let's say I want a 6x6 matrix with all zeros except for a one in row 3, column 5. Instead of literally writing in that matrix, or creating an all-zero matrix and then modifying it, I could write lookupTable(@(x,y) x==3&&y==5, 6, 6)

like image 403
traffichazard Avatar asked Feb 21 '23 21:02

traffichazard


2 Answers

I would use a combination of MESHGRID to generate 2-D input grids for x and y and ARRAYFUN to evaluate the scalar function f at each grid pair. For your first example, you can do this:

[y, x] = meshgrid(1:12, 1:12);  %# Or just [y, x] = meshgrid(1:12);
lutable = arrayfun(f, x, y);

Note that I reversed the order of the inputs and outputs to MESHGRID so that values of x increased going down the rows of the resulting lookup table.

like image 110
gnovice Avatar answered Mar 06 '23 06:03

gnovice


Something like this?

function a = lookupTable(func, cols, rows)
    a = zeros(cols, rows);
    for i = 1:cols
        for j=1:rows
            a(i,j) = func(i, j);
        end 
    end
end

called with

lookupTable(@(x,y) x==3&&y==5, 6, 6)
like image 32
Griffin Avatar answered Mar 06 '23 05:03

Griffin