1

I've noticed that in a python code you can do something like:

a=0
b=1
a,b=b,a
print(a,b)

which outputs (a=1,b=0) (i.e. each variable is assigned independently of the last assignment). Is there a way to do something similar in MATLAB?

Sorry if this is a really simple question, but I've been trying to find a clean answer to this for a bit of time now and haven't found anything.

Atreyu
  • 639
  • 2
  • 7
  • 16
  • Actually, this is a possible duplicate of [How do I do multiple assignment in MATLAB?](http://stackoverflow.com/questions/2337126/how-do-i-do-multiple-assignment-in-matlab) and [Define multiple variables at the same time in MATLAB?](http://stackoverflow.com/questions/5158032/define-multiple-variables-at-the-same-time-in-matlab). – Eitan T Dec 01 '13 at 10:16

2 Answers2

5

There is no need for an additional temporary variable here. If you want multiple assignments in a single statement, you can use deal:

[a, b] = deal(b, a)

I believe this is what you're looking for.

Eitan T
  • 32,660
  • 14
  • 72
  • 109
  • 1
    Thank you actually this is perfect. – Atreyu Dec 01 '13 at 10:09
  • 2
    Woaw, almost as pretty as in Python, nice :p – Maxime Lorant Dec 01 '13 at 10:10
  • What is the overhead of `deal` vs. just creating a temporary variable? The JIT can easily optimize away a temporary variable. Even though `deal` is not particularly complicated internally, I wonder if it's a good idea to use it when performance matters? – horchler Dec 01 '13 at 16:10
  • @horchler JIT acceleration is something fairly hard to predict (at least for me). While it can be tested, I think you're overcomplicating the question. – Eitan T Dec 01 '13 at 16:16
  • That's true if the code is overly complicated. But for simple cases of directly switching the contents of variables with a temporary variable it might be good. A test on my machine (R2013a, OS X) show that `deal` was *12 times slower* than using a temporary variable. This was constant across a wide range range of variable sizes. Convenience often has a cost. – horchler Dec 01 '13 at 16:30
2

It's always possible to do that with a temporary variable in any language. The unpacking method of Python is just a little syntax sugar to simplify the developer life :)

a = 0
b = 1
tmp = a
a = b
b = tmp
print(a,b)

Anyway, it's not magical, the Python byte code might implement the permutation with a temporary variable. (There's techniques to do this without temp variable, but well... for the sake of clarity use one :p)

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
  • yeah I should have thought of that... I guess I was too caught up with how pretty it looked in python. Forgive my novice skills :P – Atreyu Dec 01 '13 at 09:56