3
$\begingroup$

I calculated matrices which took a long calculation time and now I want to interpolate them to a function f(x,y) but I just found out that i forgot to add the coordinate data to the table which I need to add in advance now without re-calculating the actual matrices.

Here is a simplified problem which I try to tackle:

What I want:

mat = Table[{x, y, x^2 + y^2}, {x, 0, 10, 1}, {y, 0, 10, 1}];

What I have:

mat2 = Table[x^2 + y^2, {x, 0, 10, 1}, {y, 0, 10, 1}];

I created the coordinate vectors

xtab = Table[x, {x, 0, 10, 1}];
ytab = Table[y, {y, 0, 10, 1}];

but how can I smartly combine them component wise to receive the wanted matrix? I already got desperate trying.

$\endgroup$
1
  • 1
    $\begingroup$ Why not just generate tab = Table[{x, y}, {x, 0, 10, 1}, {y, 0, 10, 1}];, and then join them? $\endgroup$
    – Feyre
    Commented Feb 2, 2017 at 13:40

1 Answer 1

2
$\begingroup$

There are several possibilities to do this (and probably a lot more that I can't think of but someone else will). It depends a bit on what kind of assumptions you can make about your data and what you can change about the snippets you have up there.

For example, if you can change xtab and ytab, it would be easier to generate them as full matrices immediately, and then use a simple transposition:

xtab = Table[x, {x, 0, 10, 1}, {y, 0, 10, 1}];
ytab = Table[y, {x, 0, 10, 1}, {y, 0, 10, 1}];

Transpose[{xtab, ytab, mat2}, {3, 1, 2}]

Alternatively, if you know that x and y are simply zero-based indices, you don't need to generate xtab and ytab at all. Instead, simply use MapIndexed and compute them based on the current index:

MapIndexed[{#2[[1]] - 1, #2[[2]] - 1, #} &, mat2, {2}]

Or slightly terser:

MapIndexed[Append[#2 - 1, #] &, mat2, {2}]

Finally, if you've really only got mat2, xtab and ytab to work with, I'd probably also go for MapIndexed:

MapIndexed[{xtab[[#2[[1]]]], ytab[[#2[[2]]]], #} &, mat2, {2}]

here, I'm using the components of the current index of mat2 to index into xtab and ytab, respectively, which ensures I'm getting the right coordinate value for each of them.

$\endgroup$
1
  • $\begingroup$ The simple table joining you mentioned first in your answer already worked that out but I am also just playing around with MapIndexed to understand that. Thanks for the quick help! $\endgroup$
    – Rico
    Commented Feb 2, 2017 at 20:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.