1
$\begingroup$

There is a function f that I would like to operate on a rectangular part of a table t. The part is specified by function

Part[t, Sequence @@ (Span @@ # & /@ rect)]

This would work as I intended

Part[t, Sequence @@ (Span @@ # & /@ rect)] = Map[f, Part[t, Sequence @@ (Span @@ # & /@ rect)], {2}] ]

But I have to repeat this long, tedious Part twice. I tried alternative ways:

(*attempt 1*)
With[   {part=Part[t, Sequence @@ (Span @@ # & /@ rect)]},
        part = Map[f,part,{2}]]      ]

(*attempt 2*)
(part = Map[f,part,{2}])/.{part->Part[t, Sequence @@ (Span @@ # & /@ rect)]}

But they wouldn't work. How can I make a "reference", or a "pointer" to the part that I want to operate on, without making a copy of it? Thanks!

$\endgroup$
  • $\begingroup$ Please add minimal example and expected result. $\endgroup$ – Kuba Apr 17 '15 at 7:36
1
$\begingroup$

I'm not quite sure what you're after yet, but if you're looking to Map a function to a submatrix, try MapAt

matrix = Array[# &, {3, 3}]
MapAt[E^# &, matrix, {2 ;; 3, 2 ;; 3}] // MatrixForm

enter image description here

You could also use ReplacePart

ReplacePart[
  matrix,
  {i_?(MemberQ[{2, 3}, #] &), j_?(MemberQ[{2, 3}, #] &)} -> f@matrix[[i, j]]
  ] // MatrixForm

enter image description here

| improve this answer | |
$\endgroup$
1
$\begingroup$

You may consider

spec = Sequence @@ (Span @@ # & /@ rect);
Part[t, spec]

or

t[[spec]]

This would lead to:

With[{spec = Sequence @@ (Span @@ # & /@ rect)},
 t[[spec]] = Map[f, t[[spec]], {2}]]
| improve this answer | |
$\endgroup$

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.