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에서 Multidimensional Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!