Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

This question already has an answer here:

% 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}}*)
share|improve this question

marked as duplicate by Szabolcs, m_goldberg, Yves Klett, rm -rf Sep 17 '13 at 18:45

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
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
1  
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

2 Answers 2

up vote 5 down vote accepted
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}}

share|improve this answer
1  
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}} *)
share|improve this answer

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