3
$\begingroup$

I have two tables with diferent sizes which "represents" two discrete functions.

table1 = {{3, 5}, {13, 15}} enter image description here table2 = {{1, 2, 3, 4, 5}, {1, 0, 1, 0, 0}} enter image description here I need to obtain this result: result = {{1, 2, 3, 4, 5}, {1, 0, 14, 0, 15}} enter image description here

The result is the sum of the two "functions" with using the "domain" of the second.

Thanks!

$\endgroup$
3
$\begingroup$
ClearAll[f]
f = KeyValueMap[List] @ KeySort @ Merge[Total][AssociationThread @@@ #] &;

f[{table1, table2}] // TableForm

enter image description here

Also

ClearAll[f2]
f2 = Sort @ KeyValueMap[List] @ Merge[Total][AssociationThread @@@ #] &;

f2[{table1, table2}] // TableForm

enter image description here

$\endgroup$
0
3
$\begingroup$
table1 = {{3, 5}, {13, 15}};
table2 = {{1, 2, 3, 4, 5}, {1, 0, 1, 0, 0}};

Flatten[{table1, table2}, {3, 1}]  (*Out: {{3, 13}, {1, 1}, {5, 15}, {2, 0}, {3, 1}, {4, 0}, {5, 0}}*)
GroupBy[%, First -> Last, Total]   (*Out: <|3 -> 14, 1 -> 1, 5 -> 15, 2 -> 0, 4 -> 0|>*)
Normal[%] /. Rule -> List // Sort  (*Out: {{1, 1}, {2, 0}, {3, 14}, {4, 0}, {5, 15}}*)
$\endgroup$
0
2
$\begingroup$

I am sure there is a better way and with less code to do this may be using smart threading or some other one Mathematica cool command, but I am lazy to look for it now, so here is a quick hack

Clear["Global`*"];
table1 = Transpose[{{3, 5}, {13, 15}}];
table2 = Transpose[{{1, 2, 3, 4, 5}, {1, 0, 1, 0, 0}}];
max = Max[table1[[All, 1]], table2[[All, 1]]];
min = Min[table1[[All, 1]], table2[[All, 1]]];
range = Range[min, max];
fixTable1 = If[MemberQ[table1[[All, 1]], #], 
     First@Extract[table1, Position[table1[[All, 1]], #]], {0, 0}] & /@range;
fixTable2 = If[MemberQ[table2[[All, 1]], #], 
     First@Extract[table2, Position[table2[[All, 1]], #]], {0, 0}] & /@range;
fixed = Transpose[{range, fixTable1[[All, 2]] + fixTable2[[All, 2]]}];
TableForm[fixed, TableHeadings -> {None, {"x", "y"}}]

Mathematica graphics

$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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