matrix indexing without for loop

17 views (last 30 days)
majid
majid on 15 Feb 2014
Edited: Azzi Abdelmalek on 15 Feb 2014
hello to all. i have a 3d matrix like this:
c(:,:,1) =
5 2
1 9
c(:,:,2) =
4 7
5 6
and then i sort c with this code :
[~ ind] = sort(c,3);
now ind has these values :
ind(:,:,1) =
2 1
1 2
ind(:,:,2) =
1 2
2 1
now!! here is my question. suppose i want to have sorted matrix of c just by ind matrix and actually without for loop . can anyone help me plz ? (know that first output argument is sorted matrix. my problem is like this which i mentioned )

Answers (1)

Azzi Abdelmalek
Azzi Abdelmalek on 15 Feb 2014
Edited: Azzi Abdelmalek on 15 Feb 2014
[sorted_matrix,ind]= sort(c,3)
You can get sorted_matrix by using
[n,m,p]=size(c);
[ii,jj]=ind2sub([n,m],1:n*m);
q=sub2ind(size(c),repmat(ii',p,1),repmat(jj',p,1), ind(:));
cs1=reshape(c(q),n,m,p)
isequal(cs1,sorted_matrix) % to test the result

Community Treasure Hunt

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

Start Hunting!