# MATLAB's “logical indexing” in Mathematica [duplicate]

% MATLAB code
A=reshape(1:16,4,[])'
k=logical([1 0 0 1; 0 1 1 0; 0 1 1 0;1 0 0 1 ])
A(k)=5-A(k)
%{
4     2     3     1
5    -1    -2     8
9    -5    -6    12
-8    14    15   -11
%}


I need Mathematica code that works like the MATLAB code above. Is there a easy way do this?

A = Range[16]~Partition~4
k = {{1, 0, 0, 1}, {0, 1, 1, 0}, {0, 1, 1, 0}, {1, 0, 0, 1}}
A[[k]] = 5 - A[[k]]


Updated:

fA = Flatten[A];
p = Flatten@Position[Flatten@k, 1];
fA[[p]] = 5 - fA[[p]];
Partition[fA, 4]

(*{{4, 2, 3, 1}, {5, -1, -2, 8}, {9, -5, -6, 12}, {-8, 14, 15, -11}}*)

• You will get the answer about week earlier if you describe what do you want instead of posting code from other language. No to mention that research effort will be appreciated. – Kuba Sep 17 '13 at 12:52
• I don't want to be rude, I want to help but I have no clue what's in the first code block :) – Kuba Sep 17 '13 at 13:00

A = Range[16]~Partition~4;
k = {{1, 0, 0, 1}, {0, 1, 1, 0}, {0, 1, 1, 0}, {1, 0, 0, 1}};
A = 5 k + A (1 - 2 k)


{{4, 2, 3, 1}, {5, -1, -2, 8}, {9, -5, -6, 12}, {-8, 14, 15, -11}}

• Nice solution, but to me, at least, this is clearer if it is written as (5 k - A) (2 k - 1) – m_goldberg Sep 17 '13 at 13:58

As best as I can tell, the logical function in Matlab only applies the operation if the indicator matrix (in this case k) contains a 1 at the corresponding position.

So you could get the same result using something like this:

MapThread[If[#2 == 1, 5 - #1, #1] &, {A, k}, 2]

(* {{4, 2, 3, 1}, {5, -1, -2, 8}, {9, -5, -6, 12}, {-8, 14, 15, -11}} *)