how can i swap the matrix element using control statements or any built in functions?
2 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
Ameer Hamza
2020-11-22
编辑:Ameer Hamza
2020-11-22
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!