swap the two columns of a matrix in matlab

You can swap the two columns of a matrix in MATLAB by directly assigning the columns to each other. Here is an example:

main.m
% Create a sample matrix
A = [1, 2, 3; 4, 5, 6; 7, 8, 9];

% Swap columns 1 and 2
A(:, [1, 2]) = A(:, [2, 1]);
111 chars
6 lines

In this example, A(:, [1, 2]) = A(:, [2, 1]); swaps the first and second columns of matrix A.

related categories

gistlibby LogSnag