Set :: setps: in the part assignment is not a symbol. >>

I define a function in Mathematica, where if the i-th value in the list is 1 and the i + 1-th value is 0, the function switches these two values.

I defined it as:

f[i_, x_] := (If[x[[i]] == 1 && x[[i + 1]] == 0, x[[i]] = 1; x[[i + 1]] = 0]); 

However, when I test it with i = 2 and x = {1,1,0,0} , I get the following error:

Set :: setps: {1,1,0,0} in the part assignment is not a symbol. β†’

I do not quite understand what I am doing wrong, since I thought that I was saying everything correctly.

+4
source share
2 answers

You seem to have found a solution, but still break it.

First, you have a simple transcription error where your Set applies the original values ​​rather than replacing them. The base code works with this change:

 i = 2; x = {1, 1, 0, 0}; If[ x[[i]] == 1 && x[[i + 1]] == 0, x[[i]] = 0; x[[i + 1]] = 1; ] x 
 {1, 0, 1, 0} 

So, we have successfully changed x . To do this in a function, we must pass the name x this code, not the value x . This is the source of your error:

 {1, 1, 0, 0}[[2]] = 0; 

Set :: setps: {1,1,0,0} in the part assignment is not a symbol. β†’

You need a Hold attribute for your function:

 SetAttributes[f, HoldAll] f[i_, x_] := If[x[[i]] == 1 && x[[i + 1]] == 0, x[[i]] = 0; x[[i + 1]] = 1;] i = 2 ; x = {1, 1, 0, 0}; f[2, x] x 
 {1, 0, 1, 0} 

You may not have intended to change the value of x itself, but this method will undoubtedly come in handy in other applications. To change the function above to manage a copy of the data, we can use the Module , and we do not need the Hold attribute:

 f2[i_, xImmutable_] := Module[{x = xImmutable}, If[x[[i]] == 1 && x[[i + 1]] == 0, x[[i]] = 0; x[[i + 1]] = 1]; x ] i = 2 ; x = {1, 1, 0, 0}; f2[2, x] 
 {1, 0, 1, 0} 

Note that the x inside the Module is a local variable, not your global list of x , which remains unchanged.

For fun, let it be implemented differently.

 f3[i_, x_] := If[ x[[i + {0, 1}]] == {1, 0}, ReplacePart[x, {i -> 0, i + 1 -> 1}], x ] f3[2, x] 
 {1, 0, 1, 0} 
+3
source

I get it; I did not need to change the value of x itself. Email Oh!

0
source

Source: https://habr.com/ru/post/1439567/


All Articles