TransWikia.com

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

Mathematica Asked on January 22, 2021

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

One Answer

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

Answered by kglr on January 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP