# Performance of swapping two elements in MATLAB

Purely as an experiment, I'm writing sort functions in MATLAB then running these through the MATLAB profiler. The aspect I find most perplexing is to do with swapping elements.

I've found that the "official" way of swapping two elements in a matrix

`self.Data([i1, i2]) = self.Data([i2, i1]) `

runs much slower than doing it in four lines of code:

`e1 = self.Data(i1); e2 = self.Data(i2); self.Data(i1) = e2; self.Data(i2) = e1; `

The total length of time taken up by the second example is 12 times less than the single line of code in the first example.

Would somebody have an explanation as to why?

-------------Problems Reply------------

In the first (slow) approach, the RHS value is a matrix, so I think MATLAB incurs a performance penalty in creating a new matrix to store the two elements. The second (fast) approach avoids this by working directly with the elements.

Check out the "Techniques for Improving Performance" article on MathWorks for ways to improve your MATLAB code.

Based on suggestions posted, I've run some more tests. It appears the performance hit comes when the same matrix is referenced in both the LHS and RHS of the assignment.

My theory is that MATLAB uses an internal reference-counting / copy-on-write mechanism, and this is causing the entire matrix to be copied internally when it's referenced on both sides. (This is a guess because I don't know the MATLAB internals).

Here are the results from calling the function 885548 times. (The difference here is times four, not times twelve as I originally posted. Each of the functions have the additional function-wrapping overhead, while in my initial post I just summed up the individual lines).

swap1: 12.547 s
swap2: 14.301 s
swap3: 51.739 s

Here's the code:

``` methods (Access = public) function swap(self, i1, i2) swap1(self, i1, i2); swap2(self, i1, i2); swap3(self, i1, i2); self.SwapCount = self.SwapCount + 1; end end```

``` methods (Access = private) % % swap1: stores values in temporary doubles % This has the best performance % function swap1(self, i1, i2) e1 = self.Data(i1); e2 = self.Data(i2); self.Data(i1) = e2; self.Data(i2) = e1; end % % swap2: stores values in a temporary matrix % Marginally slower than swap1 % function swap2(self, i1, i2) m = self.Data([i1, i2]); self.Data([i2, i1]) = m; end % % swap3: does not use variables for storage. % This has the worst performance % function swap3(self, i1, i2) self.Data([i1, i2]) = self.Data([i2, i1]); end ```

```end ```

you could also do:

```tmp = self.Data(i1); self.Data(i1) = self.Data(i2); self.Data(i2) = tmp; ```

Zach is potentially right in that a temporary copy of the matrix may be made to perform the first operation, although I would hazard a guess that there is some internal optimization within MATLAB that attempts to avoid this. It may be a function of the version of MATLAB you are using. I tried both of your cases in version 7.1.0.246 (a couple years old) and only saw a speed difference of about 2-2.5.

It's possible that this may be an example of speed improvement by what's called "loop unrolling". When doing vector operations, at some level within the internal code there is likely a FOR loop which loops over the indices you are swapping. By performing the scalar operations in the second example, you are avoiding any overhead from loops. Note these two (somewhat silly) examples:

`vec = [1 2 3 4];`

``` %Example 1: for i = 1:4, vec(i) = vec(i)+1; end; ```

```%Example 2: vec(1) = vec(1)+1; vec(2) = vec(2)+1; vec(3) = vec(3)+1; vec(4) = vec(4)+1; ```

Admittedly, it would be much easier to simply use vector operations like:

```vec = vec+1; ```

but the examples above are for the purpose of illustration. When I repeat each example multiple times over and time them, Example 2 is actually somewhat faster than Example 1. For a small loop with a known number (in the example, just 4), it can actually be more efficient to forgo the loop. Of course, in this particular example, the vector operation given above is actually the fastest.

I usually follow this rule: Try a few different things, and pick the fastest for your specific problem.

Category:performance Views:0 Time:2009-02-02

## Related post

• How to swap two elements of an mpl::vector? 2011-10-28

I'm writing a template function which should swap two elements of a boost::mpl::vector (similarly to std::swap). The difficult part is there is no concept of a variable during compile time. I have written a draft but I wonder if there are better ways

• Azure - Cannot programmatically perform VIP Swap 2011-12-10

I am trying to perform a swap deployment operation, in C#, on a hosted service I have in the azure cloud. My code returns no errors, however, the swap is never performed. My code is based off sample code from the Microsoft website on how to do a list

• Javascript swap array elements 2009-05-16

Is there any simpler way to swap two elements in an array? var a = list[x], b = list[y]; list[y] = a; list[x] = b; --------------Solutions------------- You only need one temporary variable. var b = list[y]; list[y] = list[x]; list[x] = b; If you want

• Need a function in javascript to swap 2 elements in an array 2010-04-14

A program to swap two numbers /* /* Function to swap two numbers. Function takes an argument which is an array of two elements. Function returns a new array containing the same two elements as the argument array but in reverse order. */ function swap

• How do I swap array elements using parallel assignment? 2010-11-15

I am trying to swap two elements in an array like this deck = [] (deck << (1..52).to_a << 'A' << 'B').flatten! p deck deck[deck.index("A")], deck[deck.index("B")] = deck[deck.index("B")], deck[deck.index("A")] #swap "A" and "B" p de

• How to swap map elements 2010-11-20

In C++, how would I swap two elements of a map? --------------Solutions------------- What do you mean by swap in a map? A normal plain vanila map doesn't have any particular order so speaking of swapping has no meaning in reference to order. If you a

• Flex: Swapping two elements in Array Collection 2011-04-26

What's the best-approach to swap to elements in a Flex Array Collection? I am binding a ArrayCollection as a dataprovider to combo-box. Selecting a row, should move the object to the top of the combo-box list, and move the top-object to selected obje

• Erlang swap two element in list 2011-05-26

How can I quickly swap two elements in Erlang list? For example I have list: [1,2,3,4], how can I quickly get [1,3,2,4]? --------------Solutions------------- You did not say in your question how you want to specify which two element you want to swap.

• Comparing adjacent elements in MATLAB 2010-02-13

Does anyone know how I can compare the elements in an array with the adjacent elements? For example, if I have an array: 0 0 0 1 1 1 1 0 0 1 1 1 1 1 1 0 0 1 0 1 1 1 1 0 0 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 Is there a way to cycle through e

• Swap List elements with c# using LINQ 2009-07-10

I have this list var list = new List { 3, 1, 0, 5 }; I want to swap element 0 with 2 output 0, 1, 3, 5 --------------Solutions------------- If you just want it sorted, I'd use List.Sort(). If you want to swap, there is no built in method to do this.

• Performant intersection and distinct element extraction? 2009-11-05

I have a line like the following in my code: potentialCollisionsX.Intersect(potentialCollisionsY).Distinct().ToList(); Which, through profiling, i have determined that it is eating approximately 56 percent of my time. I need to figure out how to prov

• Finding whether a value is equal to the value of any array element in MATLAB 2010-03-14

Can anyone tell me if there is a way (in MATLAB) to check whether a certain value is equal to any of the values stored within another array? The way I intend to use it is to check whether an element index in one matrix is equal to the values stored i

• jquery fade an element in when a link is clicked and then swap the element when another link is clicked 2010-04-30

I have worked out how to fade an element in: Click here to view the page If you click on the heading Posture 1 : Standing Deep Breathing : you will notice the element fades in as it should. If you now click on posture 2 you will see the element fades

• How to swap HTML elements in javascript? 2010-05-31

I am using classic Javascript for DOM scripting, i have a set of DIV's in a container DIV. On click event of child DIV's, i want that the child DIV which has caused event to be swaped with the DIV above it.. my code goes here.. <div id="container"

• how to swap array-elements to transfer the array from a column-like into a row-like representation 2010-06-09

For example: the array a1, a2, a3, b1, b2, b3, c1, c2, c3, d1, d2, d3 represents following table a1, b1, c1, d1 a2, b2, c2, d2 a3, b3, c3, d3 now i like to bring the array into following form a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3 Does an alg

• What's a good and functional way to swap collection elements in Scala? 2010-07-26

In a project of mine one common use case keeps coming up. At some point I've got a sorted collection of some kind (List, Seq, etc... doesn't matter) and one element of this collection. What I want to do is to swap the given element with it's followin

• Right way to swap x elements in List 2010-08-31

I started to learn Scala language and I have a question. How do you think, is it a right way to swap first and last x elements in List in a functional style? def swap(l: List[Any], x: Int) = { val l1 = l.take(x) val l2 = l.slice(x, l.length - x) val

• How do I extract matrix elements in matlab? 2010-09-18

Possible Duplicates: MATLAB Easiest way to assign elements of a vector to individual variables. How do I do multiple assignment in MATLAB? If I have a matrix: A = [1, 5, 10], do I set a1 = A(1), b1 = B(1), etc. on one line? I want to do something lik

• Performance penalty of persistent variables in MATLAB 2010-09-26

Recently I profiled some MATLAB code and I was shocked to see the following in a heavily used function: 5.76 198694 58 persistent CONSTANTS; 3.44 198694 59 if isempty(CONSTANTS) % initialize CONSTANTS In other words, MATLAB spent about 9 seconds, ove

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.086 (s). 11 q(s)