Column Operation - Subtract part of nested list from part of another nested list [duplicate]

I have two lists with x- and y-coordinates with different z-coordinates of the form

{{x0, y0, z0_1}, {x1, y1, z1_1}, ..., {xn, yn, zn_1}}


and

{{x0, y0, z0_2}, {x1, y1, z1_2}, ..., {xn, yn, zn_2}}.


I want to construct the list

{{x0, y0, z0_1 - z0_2}, {x1, y1, z1_1 - z1_2}, ..., {xn, yn, zn_1 - zn_2}}


i.e. construct a list containing the difference of only the z-coordinates, for each x- and y-coordinate.

Is it possible to do this with a few simple commands, or should I construct a loop and create a new list from scratch?

marked as duplicate by Mr.Wizard♦Sep 12 '14 at 13:57

• Have a look at Transpose and Differences. – b.gates.you.know.what Sep 12 '14 at 13:27
• Thank you :) I didn't find a solution before another answer was given to me however. – bjorn Sep 12 '14 at 13:42

lis1 = {{x0, y0, z01}, {x1, y1, z11}, {xn, yn, zn1}};
lis2 = {{x0, y0, z02}, {x1, y1, z12}, {xn, yn, zn2}};


If you first define this function:

f[{x_, y_, z_}, {x_, y_, u_}] := {x, y, z - u}


You can then easily do:

f @@@ Transpose[{lis1, lis2}]

{{x0, y0, z01 - z02}, {x1, y1, z11 - z12}, {xn, yn, zn1 - zn2}}

• Thank you very much. That works perfectly! :) – bjorn Sep 12 '14 at 13:42
• @bjorn, you're welcome. – RunnyKine Sep 12 '14 at 13:43

Consider:

a = {{x0, y0, z0}, {x1, y1, z1}, {xn, yn, zn}};
b = {{x0, y0, Z0}, {x1, y1, Z1}, {xn, yn, Zn}};  (* note capital Z *)

c = a;
c[[All, 3]] -= b[[All, 3]];
c

{{x0, y0, z0 - Z0}, {x1, y1, z1 - Z1}, {xn, yn, zn - Zn}}


You can use a Module if you wish to make this a self-contained function.

Another option (looks better in a Notebook):

{#, #2, #3 - b[[All, 3]]}\[Transpose] & @@ (a\[Transpose])

• Should the question be closed then as a duplicate? – RunnyKine Sep 12 '14 at 13:51
• @RunnyKine I guess this really should be closed so I'll convert my answer to CW and do it. – Mr.Wizard Sep 12 '14 at 13:57
• Thank you very much as well. It's nice having different solutions :) And I'm sorry for not finding that the questions had already been answered, I tried to but was a bit unsure of what to search for exactly. Of course I don't oppose a close, but I suppose that the thread will still be viewable for future visitors? – bjorn Sep 12 '14 at 14:00
• @bjorn I always appreciate people searching before posting but I also know that finding existing Q&A's can be quite difficult. I've spent 15-20 minutes looking for a single one without result before. This question will remain for a time; it may or may not be deleted some months from now. I am not sure how many people would find this question given its current title, but that may be only my own bias speaking. (It seems like a column operation to me so I would phrase it as such but that is merely an opinion.) – Mr.Wizard Sep 12 '14 at 14:09