matrix indexing without for loop

17 次查看(过去 30 天)
majid
majid 2014-2-15
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 )

回答(1 个)

Azzi Abdelmalek
Azzi Abdelmalek 2014-2-15
编辑:Azzi Abdelmalek 2014-2-15
[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

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by