Is it possible to use a list as a variable, i.e., to pass it by reference to a function?
In particular, I have a two-dimensional array and a function to get one element specified by its position:
s = {{1, 1, 1, -1}, {1, 1, -1, -1}, {-1, -1, 1, -1}, {-1, 1, -1, 1}};
valueAtPos[positionX_, positionY_, lattice_List] :=
Flatten[Take[lattice, {positionY, positionY}, {positionX, positionX}]]
This works just fine, it does exactly what I want.
Now, what I'm actually aiming at is "flipping" the value at a certain position, i.e. $-1 \rightarrow 1$ and vice versa. I tried it with a function and a fixed list and it worked, but since I have more than one list, I want to pass the actual list not a copy as an argument as well. So I tried this:
flip[posX_, posY_, lattice_List] :=
Module[{latticeLocal = lattice, x = posX, y = posY},
latticeLocal =
ReplacePart[latticeLocal, {y,x} -> -valueAtPos[x, y, latticeLocal]] //.
{{1} :> 1, {-1} :> -1};]
If I run, for example, flip[1, 1, s]
, it should change s
to
s = {{-1, 1, 1, -1}, {1, 1, -1, -1}, {-1, -1, 1, -1}, {-1, 1, -1, 1}}.
but it doesn't; s
is left untouched, exactly the same as before. If I run
s = ReplacePart[s,{1,1} -> -valueAtPos[1, 1, latticeLocal]] //. {{1} :> 1, {-1} :> -1};
it does exactly what it's supposed to do.
My question is: How can I pass a list, not a copy of the list, to a function so the list I pass will really get modified.
(I tried using the list like a normal argument of a function and I got errors. Modules, at least, didn't give me errors)
Edit
Nasser told me to delete the semicolon in flip
and to assign the output of the function to my original list. That works, of course, but is not quite what I wanted, so I am going to clarify this here.
I want to use the flip
in another function. And I not only want to run the function, I also want to use its output. Look at this:
algorithm[steps_, T_, lattice_List] :=
Module[{latticeLocal = lattice},
For[i = 0, i < steps, i++,
{
(* definig some variables inside the for-loop *)
If[(* some expression *),
latticeLocal = flip[posX, posY, latticeLocal],
0]
}];]
This doesn't work. I need to use the output of flip
in the for-loop, and I don't have an idea how to do that.
;
at the end of your function, and assign the result tos
, like this: !Mathematica graphics $\endgroup$s
$\endgroup$