How to change an element in matrix, based on equality of other elements?

I have following problem. I can solve it without any real troubles using 2 for cycles. Knowing it is not really a Mathematica friendly approach, can you give me suggestions of a nice Mathematica code? I have two arrays of random numbers and where these numbers are equal to each other, I have to add +1 to original values of these elements and make a final matrix: matrix1.

capacityofLines = {55, 63, 87, 45, 61, 45, 69, 87};

randomExample = {55, 63, 87, 45, 20, -30, 69, 120};

equalszero = capacityofLines - randomExample;

equals = Position[equalszero, _?(# == 0 &)] // Flatten

{1, 2, 3, 4, 7}

matrix1 = Table[capacityofLines, Length[equals]];

matrix2 = Table[capacityofLines, Length[equals]];
matrix3 = Table[x, Length[equals]];

For[i = 1, i <= Length[equals], i++,
matrix3[[i]] = capacityofLines[[equals[[i]]]] + 1]

For[i = 1, i <= Length[equals], i++,
matrix1[[i, equals[[i]]]] = matrix3[[i]]]

matrix1 // TableForm • could you post capacityofLines?
– kglr
Nov 30 '20 at 19:57
• Working backwards, from equalszero, capacityofLines must be {55, 63, 87, 45, ??, 69, ??}. I guess the actual values don't matter as long as they are different from the corresponding values in randomExample. Nov 30 '20 at 20:07
• In fact, when one edits OP's code, the definition capacityofLinesis here. It seems that the OP has difficulties with the editor. Nov 30 '20 at 20:13
• OP's question corrected. Hope my corrections are OK. Nov 30 '20 at 20:21

capacityofLines = {55, 63, 87, 45, 61, 45, 69, 87};

randomExample = {55, 63, 87, 45, 20, -30, 69, 120};

equalszero = capacityofLines - randomExample;

equals = Position[equalszero, _?(# == 0 &)] // Flatten
{1, 2, 3, 4, 7}

Given capacityofLines and equals you can get your matrix1 in a single step as follows:

matrix1 = MapAt[# + 1 &, Table[capacityofLines, Length[equals]],
Transpose[{Range@Length@equals, equals}]];

matrix1 // TableForm Alternatively,

sa = SparseArray[Transpose[{Range@Length@equals, equals}] -> 1,
Length /@ {equals, capacityofLines}];

matrix1b = Table[capacityofLines, Length[equals]] + sa;

matrix1b == matrix1
True

Taking capacityOfLines and randomExample as input, we can do

matrix1c = Module[{pos = MapIndexed[Join[#2, #] &,
SparseArray[1 - Unitize[capacityofLines - randomExample]]["NonzeroPositions"]]},
MapAt[# + 1 &, Table[capacityofLines, Length@pos], pos]];

matrix1c == matrix1
True
• NIce. Thank zou for the answer Dec 1 '20 at 13:40