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.

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you actually this is perfect.
Woaw, almost as pretty as in Python, nice :p
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 JIT acceleration is something fairly hard to predict (at least for me). While it can be tested, I think you're overcomplicating the question.
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.
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)

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.