2
$\begingroup$

Assuming variable x is a long list, which needs 1GB memory to store.

I want to modify x in a function, such as let x[[10]]=1, using

f[a_,i_]:=Block[{b},b=a;b[[i]]=1;b]
x=f[x,10]

but when I call the funtion f, it will take extra 1GB memory. How can I in-situ modify x in function f without extra memory?

$\endgroup$

marked as duplicate by Kuba Nov 25 '18 at 16:53

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.

  • 2
    $\begingroup$ SetAttributes[foo, HoldFirst]; foo[a_, i_]:=a[[i]] = 1? $\endgroup$ – Kuba Nov 25 '18 at 15:37
  • $\begingroup$ @Kuba it works well! thank you. $\endgroup$ – cmc Nov 25 '18 at 16:38
  • $\begingroup$ Additional reading: mathematica.stackexchange.com/a/18737/5478 $\endgroup$ – Kuba Nov 25 '18 at 16:53

Browse other questions tagged or ask your own question.