matlabmatrixjulialinear-algebra

Easiest way to Swap Rows in Julia


I want to swap two specific rows of a Matrix. I do not want to write a second function just for that and I am looking for the easiest/quickest way possible.

In Matlab or Octave in order to swap the k-th and r-th row of a Matrix A we could simply write:

A([k r],:) = A([r k],:)

When I try this on Julia (VsCode) I get this error: ERROR: LoadError: syntax: "[k r]" is not a valid function argument name around File Path

Is there another way? I do not want to have a function just to swap rows. Thanks in advance


Solution

  • In Julia, as in Numpy, you index into arrays using square brackets, unlike in Matlab where indexing uses regular parentheses.

    So when you write A([k r],:), it is interpreted as a function call. Changing it to

    A[[k r], :] = A[[r k], :]
    

    works. But it is more idiomatic to index with vectors than with matrices, so add commas, like this:

    A[[k, r], :] = A[[r, k], :]
    

    You said 'easiest', but if you care at all for performance, then the following is much, much faster, and uses no memory:

    function swaprows!(A, k, r)
        for i in axes(A, 2)
            (A[k, i], A[r, i]) = (A[r, i], A[k, i])
        end
    end