how can i swap the matrix element using control statements or any built in functions?

3 views (last 30 days)
i have a square matrix m*n, (256*256). i am looking for functions (forward and reverse) to swaps elements until the bottom-right corner remain with lower values than any other part of the matrix, and and the top-left corner with high values. example
A=[6 5;4 7] become B=[7 6;5 4]; or D=[10 20 50 60;33 55 44 100; 3 6 12 9;4 2 1 3] become E=[100 60 55 50; 44 33 20 12;10 9 6 4;3 3 2 1];
here are sample of the code I design which does not provide the answer as i needed when i applied to 256*256 matrix.
a= [6 5;4 7];
[ b ] = swaps( a );
disp(b);
function [ b ] = swaps( a )
[m,n]=size(a);
for i=1:m
for j=1:n
temp=zeros();
if a([i,j]) >= a([i,j+1])
a([i,j])=a([i,j]);
else
temp(i,j)=a(i,j);
a(i,j)=a(i,j+1);
a(i,j+1)=temp(i,j);
if a([i,j+1]) >= a([i,j+1])
a([i,j+1])=a([i,j+1]);
else
temp([i,j+1])=a([i,j+1]);
a([i,j+1])=a([i+1,j+1]);
a([i+1,j+1])=temp([i,j+1]);
end
end
end
end
i thought the same method used to access element in other programming language could be applicable in MATLAB, by referencing the element in terms of (i,j) and encrements when needed.
Can any one help me on that?

Accepted Answer

Ameer Hamza
Ameer Hamza on 22 Nov 2020
Edited: Ameer Hamza on 22 Nov 2020
You can just use sort() with reshape()
D = [10 20 50 60;33 55 44 100; 3 6 12 9;4 2 1 3]
E = reshape(sort(D(:), 'descend'), size(D)).'
Result
>> E
E =
100 60 55 50
44 33 20 12
10 9 6 4
3 3 2 1
  4 Comments

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!