# Make a table for a function that varies depending on the argument ranges

I would like to create a Table for the value of a function $$f(x,y)$$, the form of which changes depending on the ranges of $$x$$ and $$y$$. For instance, $$f=x+y$$ for $$x\in [1,2]$$ and $$y\in [0,1]$$ while $$f=x-y$$ for $$x\in [2,3]$$ and $$y\in [1,2]$$.

I tried the following code, which didn't work.

Flatten[Table[{{x + y, x, y}, {x, 1, 2, 0.1}, {y, 0, 1, 0.1}}, {{x - y, x, y}, {x, 2, 3, 0.1}, {y, 1, 2, 0.1}}], 1] // TableForm


Any help would be greatly appreciated!

• Just define your function as a piecewise function and build the table of values as normal? – Kevin Ausman Jul 18 at 18:40
• @KevinAusman: Thanks! Since this code is part of a larger project, I'm seeking a solution that uses the current format as much as possible. Would this be possible? – ppp Jul 18 at 18:44

Here is a way to salvage your attempt to get the values in the form I believe you were trying to get them in:

spec = {
{{x + y, x, y}, {x, 1, 2, 0.1}, {y, 0, 1, 0.1}},
{{x - y, x, y}, {x, 2, 3, 0.1}, {y, 1, 2, 0.1}}
};
Flatten[Table @@@ spec, 1]


But this question also brings to mind Piecewise, which can be used to express functions like the one in your question:

f = Piecewise[{
{x + y, 1 <= x < 2 && 0 <= y < 1},
{x - y, 2 <= x <= 3 && 1 <= y <= 2}
}] You can now get the table of values like this:

values = Table[f, {x, 1, 3, 0.1}, {y, 0, 2, 0.1}];

• Thanks so much! It works! – ppp Jul 19 at 16:10