I am familiar with some boolean operators. I want to access an operator that does a procedure same as below one. But for simplicity, we can say in the first step we ignore i and jth part of lists in order to use above operators. But for i and jth part we just add them to each other. I mean

IF except i and j according elements of two lists are different, the output has to be zero. For example in {0,1,0,0,1},{1,1,0,0,1} the first element of the first list is 0 but the first element of the second list is 1. The result has to be zero. but if there is not a such situation, I mean even if i and j be different but other elements are accordingly (one by one) equal, the result has to be in a such way that i and jth parts added accordingly but instead of other element must be put zero.

Assume: i=2;j=5;
  • $\begingroup$ What do you mean by "can be added"? $\endgroup$ – Jens Jul 6 '17 at 20:12
  • $\begingroup$ must be added. not can be. so sorry $\endgroup$ – Inzo Babaria Jul 6 '17 at 20:18
  • $\begingroup$ Why are the third and sixth outputs 0? $\endgroup$ – Mr.Wizard Jul 6 '17 at 20:37
  • $\begingroup$ @Mr.Wizard: If I had to guess: The output is 0 if the elements at indexes other than i/j differ, otherwise it's the sum of the two arguments, with 0 everywhere except postions i and j $\endgroup$ – Lukas Lang Jul 6 '17 at 20:45
  • $\begingroup$ One possible implementation that reproduces your outputs is: Operator[i__][l__] := If[With[{d = {l}\[Transpose]}, And @@ Equal @@@ d[[Complement[Range@Length@d, {i}]]]], Normal[Total@{l} SparseArray@Thread[{i} -> 1]], 0] (used as Operator[i,j][...]) - but without a clearer explanation we can't be sure what exactly it is you want $\endgroup$ – Lukas Lang Jul 6 '17 at 21:01

Now that you have clarified what you want, I'll post my (slightly modified) attempt from the comments as an answer:

Operator[i__][o__] :=
  Equal @@ {o}[[All, Complement[Range@Length@First@{o}, {i}]]],
   Total@{o} SparseArray@Thread[{i} -> 1]

It is used as

MyOp = Operator[2,5]

(works with an arbitrary amount of operands and indexes)

How it works:

  • Complement[Range@Length@First@{l}, {i}] gets all indexes except the specified ones
  • These indexes are then extracted from All operands {o}
  • If the resulting lists are Equal:
    • Take the Total of all operands (element wise)
    • Multiply the result (element wise), with array where only indexes {i} are 1, the rest is 0
  • Otherwise, return 0
  • $\begingroup$ Thank you so much for your answer. Unfortunately I was traveling and I could not check your answer sooner. $\endgroup$ – Inzo Babaria Jul 14 '17 at 12:34

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.