I am given a list

a = {1.1,2.1,3.1,4.1,...}

As you can see this is not a list of the form


Now I was wondering whether it is possible to write a swap function


which would swap the first and third entry such that I get


As a result.

Any help will be greatly appreciated !

If it is not possible please just tell me then I'll start looking for other ways to approach this problem.

  • $\begingroup$ I do not understand is this statement: "So I cannot target single entries using a command like [...]". Moroever, please adopt the habit of positing complete minimal examples. Mentioning the symbol MinVarGeneralThermal1 is totally irrelevant for the problem at hand, isn't it? You question is merely about reording a given list. $\endgroup$ – Henrik Schumacher Feb 19 '19 at 11:09
  • $\begingroup$ You are right, I corrected the name of the function. What I meant with 'function1[T, E, d][[2]]' is that this allows to target a single entry of a list, which would correspond to {2.1} in my example $\endgroup$ – CatoMaths Feb 19 '19 at 11:16
  • $\begingroup$ I took the freedom to modify your post in order to remove the function. Please check whether this is in accordance with your actual question. Also, please rephrase the part "So I cannot target single entries using a command like [...]" because I still don't get what you are asking for. $\endgroup$ – Henrik Schumacher Feb 19 '19 at 11:20
  • $\begingroup$ Oh well, this statement was written to help the readers understand my issue. But it is not necessary to understand the problem by any means. I will delete it. And thank you for the edit ! $\endgroup$ – CatoMaths Feb 19 '19 at 11:33
  • $\begingroup$ Dupe of 191781? $\endgroup$ – Christopher Lamb Feb 19 '19 at 17:14
a = {1.1, 2.1, 3.1, 4.1};

swap[a_, {i_, j_}] := Module[{b = a},
  b[[{j, i}]] = b[[{i, j}]];

swap[a, {3, 1}]

{3.1, 2.1, 1.1, 4.1}

Alternatively, you may also use ReplacePart as follows:

swap[a_, {i_, j_}] := ReplacePart[a, {i -> a[[j]], j -> a[[i]]}]

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.