-1
$\begingroup$
% 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}}*)
$\endgroup$
  • 1
    $\begingroup$ 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. $\endgroup$ – Kuba Sep 17 '13 at 12:52
  • 1
    $\begingroup$ I don't want to be rude, I want to help but I have no clue what's in the first code block :) $\endgroup$ – Kuba Sep 17 '13 at 13:00
5
$\begingroup$
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}}

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

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}} *)
| improve this answer | |
$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.