Search code examples
arraysmatlabcell-array

Is there an idiomatic way to exchange two elements in a cell array?


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]

Solution

  • 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