min/max indexing of array
    5 views (last 30 days)
  
       Show older comments
    
I have an array of values of the size (n,1,4), that contains Euclidian distances of vectors as well as some NaN values where the Euclidian distance is not applicable. An example of such a vector could be
E(:,:,1) =
  NaN
  722.6494
  948.3222
E(:,:,2) =
  286.7571
  NaN
  386.2155
E(:,:,3) =
  NaN
  NaN
  115.6732
E(:,:,4) =
  715.2429
  227.8121
  NaN
I want to set all but the minimum values along the 3:d dimension to NaN, but can't figure out how to use the indexing from min. I understand that
[~,I] = min(E,[],3)
Gives me the index value for each row, so in the above case I = [1, 4, 3].' - but how do I use this index in a meaningful sense to index the values I want to keep?
0 Comments
Accepted Answer
  Stephen23
      
      
 on 19 Jun 2018
        
      Edited: Stephen23
      
      
 on 19 Jun 2018
  
      Using a logical comparison is much simpler:
>> E(bsxfun(@ne,E,min(E,[],3))) = NaN
E =
ans(:,:,1) =
      NaN
      NaN
      NaN
ans(:,:,2) =
   286.76
      NaN
      NaN
ans(:,:,3) =
      NaN
      NaN
   115.67
ans(:,:,4) =
      NaN
   227.81
      NaN
Or the same for MATLAB versions with implicit array expansion (R2016b+):
E(E~=min(E,[],3)) = NaN
If you really need to use indexing then you will need to generate the subscript indices and then convert them into linear indices, e.g. using ndgrid and sub2ind:
[~,I] = min(E,[],3);
S = size(E);
S(end+1:4) = 1;
[R,C,~,F] = ndgrid(1:S(1),1:S(2),1,1:S(4));
X = sub2ind(S,R,C,I,F);
F = E;
F(:) = NaN;
F(X) = E(X)
giving exactly the same output:
F =
ans(:,:,1) =
      NaN
      NaN
      NaN
ans(:,:,2) =
   286.76
      NaN
      NaN
ans(:,:,3) =
      NaN
      NaN
   115.67
ans(:,:,4) =
      NaN
   227.81
      NaN
More Answers (0)
See Also
Categories
				Find more on Logical in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
