matrix indexing without for loop

17 ビュー (過去 30 日間)
majid
majid 2014 年 2 月 15 日
編集済み: Azzi Abdelmalek 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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by