Preserving the shape of the indices vector when indexing into another vector.
    9 Ansichten (letzte 30 Tage)
  
       Ältere Kommentare anzeigen
    
Suppose i have a vector of values A
A = [5 10 15 20 25];
And a vector of indeces that may have any number of singleton leading dimensions, e.g.
idx = zeros(1,1,3);
idx(:) = 1:3
    idx(:,:,1) =
         1
    idx(:,:,2) =
         2
    idx(:,:,3) =
I want to get the elements of A specified by the subscripts in idx, and I want the output B to have the same dimensions as idx. In this example, what I want to get is
B(:,:,1) =
     5
B(:,:,2) =
    10
B(:,:,3) =
    15
Instead of the default indexing behaviour which would get me:
B = A(idx)
    B =
         5    10    15
I know that i could obtain this by first initializing B to have the same size of idx, i.e.
B = zeros(size(idx));
B(:) = A(idx);
However, in my application, I am developing a toolbox that must be able to work with user-created functions. I can act on idx, which will be fed as an input to the user-created function, but the rest is up to the user and I cannot expect him to write these two lines of code.
Is there any way to achieve this?
4 Kommentare
  Bruno Luong
      
      
 am 16 Okt. 2020
				Yeah but not a word about "generalized" vector as with Federico's example. And documented on a blog is kind of light evidence.
Antworten (1)
  Ameer Hamza
      
      
 am 16 Okt. 2020
        
      Bearbeitet: Ameer Hamza
      
      
 am 16 Okt. 2020
  
      This can be one of the way
B = reshape(A(idx), size(idx));
Although, I wonder is why MATLAB does not follow normal behavior for indexing A(idx). Maybe there is a good reason, or maybe this is an oversight.
4 Kommentare
  Ameer Hamza
      
      
 am 22 Okt. 2020
				
      Bearbeitet: Ameer Hamza
      
      
 am 22 Okt. 2020
  
			I don't think that overloading subsindex will help here. subsindex only returns the indexes, but as we already saw, the shape of indexes have no effect on the output of indexing when idx is 1x1x3.
Siehe auch
Kategorien
				Mehr zu Performance and Memory finden Sie in Help Center und File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



