Swap the first & last columns of a matrix

Flip the outermost columns of matrix , so that the first column becomes the last and the last column becomes the first. All other columns should be left intact. Return the result in matrix form.

If the input has one column, the output should be identical to the input.

Example:

Input A = [ 12 4 7

                  5 1 4 ];

Output B is [ 7 4 12

                     4 1 5 ];

MATLAB CODE:


clc
x=input('Enter the matrix:');
[r c]=size(x);
y=[];
for i=1:r
    for j=1:c
        if(j==1)
            y(i,j)=x(i,c);
        elseif(j==c)
            y(i,j)=x(i,1);
        else
            y(i,j)=x(i,j);
        end
    end
end

Explanation:



            
            
Output:


Function:


function y = swap_ends(x)
[r c]=size(x);
y=[];
k=1;
l=c;
for i=1:r
for j=1:c
if(j==1)
y(i,j)=x(i,l);
elseif(j==c)
y(i,j)=x(i,1);
else
y(i,j)=x(i,j);
end
end
end
end

No comments