I have a Table of values e.g.
{{x,y,z},{x,y,z},{x,y,z}…}
How do I replace the the "z" column with a List of values?
I have a Table of values e.g.
{{x,y,z},{x,y,z},{x,y,z}…}
How do I replace the the "z" column with a List of values?
If you mean each column in each respective sublist with the respective value from the value list, the first, if you mean replacing all with a literal list, the second.
test = {{a, b, c}, {d, e, f}, {g, h, i}}
test[[All, 3]] = {1, 2, 3};
test
test[[All, 3]] = Sequence[{1, 2, 3}];
test
(*
{{a, b, 1}, {d, e, 2}, {g, h, 3}}
{a, b, {1, 2, 3}}, {d, e, {1, 2, 3}}, {g, h, {1, 2, 3}}
*)
fun[u_, c_, r_] := Transpose@ReplacePart[Transpose[u], c -> r]
Example:
list = {{a, b, c}, {a, b, c}, {a, b, c}};
fun[list, 1, Range[3]]
yields:
{{1, b, c}, {2, b, c}, {3, b, c}}
This requires the replacement column be the same length (which I have assumed as intention) as final transpose will fail if this is not the case.
list = {{x, y, z}, {x, y, z}, {x, y, z}};
v = {3, 1, 6};
Using ReplacePart
ReplacePart[list, {i_, 3} :> v[[i]]]
{{x, y, 3}, {x, y, 1}, {x, y, 6}}
With MapThread and Splice (new in 12.1)
MapThread[{Splice @ Most @ #1, #2} &, {list, v}]
{{x, y, 3}, {x, y, 1}, {x, y, 6}}
Using ArrayRules and ReplacePart:
list = {{x, y, z}, {x, y, z}, {x, y, z}};
v = {3, 1, 6};
RepCol[m_, c_, p_] := Module[{arules},
arules = Most @ ArrayRules @ m;
ReplacePart[m,
Thread[
Rule[
Part[Cases[arules, Rule[{x_, y_}, z_] /; Equal[y, p]],
All, 1
],
c
]
]
]
];
RepCol[list, v, 2]
({{x, 3, z}, {x, 1, z}, {x, 6, z}})
RepCol[list, v, 3]
({{x, y, 3}, {x, y, 1}, {x, y, 6}})
Or using BlockMap and MapAt:
RepCol[m_, c_, p_] := Table[
First[
BlockMap[
Function[
MapAt[Function[x, (x + Part[c, i]) - x],
#, {p}
]
],
Flatten @ m, Length @ m
]
],
{i, Length @ m}
];
RepCol[list, v, 2]
({{x, 3, z}, {x, 1, z}, {x, 6, z}})
RepCol[list, v, 3]
({{x, y, 3}, {x, y, 1}, {x, y, 6}})