5

I know that I can write it like this:

tmp = arr{i}
arr{i} = arr{j}
arr{j} = tmp

But is there a simpler way? For instance, in Python I'd write:

arr[i], arr[j] = arr[j], arr[i]
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490

2 Answers2

8

Standard, idiomatic way:

Use a vector of indices:

arr([i j]) = arr([j i]); %// arr can be any array type

This works whether arr is a cell array, a numerical array or a string (char array).


Not recommended (but possible):

If you want to use a syntax more similar to that in Python (with a list of elements instead of a vector of indices), you need the deal function. But the resulting statement is more complicated, and varies depending on whether arr is a cell array or a standard array. So it's not recommended (for exchanging two elements). I include it only for completeness:

[arr{i}, arr{j}] = deal(arr{j}, arr{i}); %// for a cell array
[arr(i), arr(j)] = deal(arr(j), arr(i)); %// for a numeric or char array
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Thank you, that's exactly what I am looking for. Having no real experience of MATLAB I get insanely confused by all the different types of brackets, when to use them, and so on. Thanks for answering such a simple noob question. – David Heffernan Sep 08 '14 at 11:23
  • 1
    I have quite some experience in Matlab and get confused also, specially with curly braces. So don't feel discouraged by that :-) – Luis Mendo Sep 08 '14 at 11:24
  • 2
    @DavidHeffernan Here is the mini tutorial: square brackets `[]` for concatenation into an array, round brackets `()` for function calls and accessing elements, and curly brackets `{}` for accessin the *content* of elements (mostly relevant for cell arrays) and concatenation into a cell array. – Dennis Jaheruddin Sep 08 '14 at 11:45
2

Not to confuse things, but let me another syntax:

[arr{[i,j]}] = arr{[j,i]};

or

[arr{i},arr{j}] = arr{[j,i]};

The idea here is to use comma-separated lists with curly-braces indexing.

Remember that when working with cell-arrays, ()-indexing gives you a sliced cell-array, while {}-indexing extracts elements from the cell-array and the return type is whatever was stored in the specified cell (when the index is non-scalar, MATLAB returns each cell content individually as a comma-separated list).

Amro
  • 123,847
  • 25
  • 243
  • 454