2
$\begingroup$

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  

enter image description here

$\endgroup$
4
  • 2
    $\begingroup$ could you post capacityofLines? $\endgroup$ – kglr Nov 30 '20 at 19:57
  • $\begingroup$ 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. $\endgroup$ – Rohit Namjoshi Nov 30 '20 at 20:07
  • $\begingroup$ In fact, when one edits OP's code, the definition capacityofLinesis here. It seems that the OP has difficulties with the editor. $\endgroup$ – andre314 Nov 30 '20 at 20:13
  • 1
    $\begingroup$ OP's question corrected. Hope my corrections are OK. $\endgroup$ – andre314 Nov 30 '20 at 20:21
3
$\begingroup$
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

![enter image description here

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
$\endgroup$
1
  • $\begingroup$ NIce. Thank zou for the answer $\endgroup$ – Jakub Petrůj Dec 1 '20 at 13:40

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.