Indexing an array with a vector
Mostrar comentarios más antiguos
I would like to index an N-dimensional array with a vector of length N. In particular, for the 2-dimensional case I am currently doing the following.
A = rand(10);
v = randi(10,1,2);
v = num2cell(v);
A(v{:})
However, this approach seems horribly inefficient. Is there not a smarter way to convert the vector v to a proper index (comma-separated) for the array A?
Edit Let's say v = randi(10,1,2) = [ 3 5 ]. In that case, I want to obtain A(3,5).
4 comentarios
This could be the best solution already, for an array of arbitrary number of dimensions. Why do you think that this method "seems horribly inefficient"? Did you run the profiler on your code and find that this operation took the most time?
Walter Roberson
el 7 de Ag. de 2015
You can improve performance slightly by assigning the transpose to p1_off ahead of time, equivalent to if I had written
Aoff = cumprod([1 As(1:end-1)]) .';
and then just use * Aoff rather than * Aoff.'
Also the "-1" was important to add to the indices. It probably can be rolled into the calculation of the offset at the expense of clarity.
Jori
el 7 de Ag. de 2015
Respuesta aceptada
Más respuestas (1)
Azzi Abdelmalek
el 7 de Ag. de 2015
Editada: Azzi Abdelmalek
el 7 de Ag. de 2015
A = rand(10);
v = randi(10,1,2)
Why converting to cell array? just type
A(v)
If v is a cell array, convert it to a double array
A = rand(10);
v = randi(10,1,2);
v = num2cell(v);
A([v{:}])
4 comentarios
Jori
el 7 de Ag. de 2015
Azzi Abdelmalek
el 7 de Ag. de 2015
You can use sub2ind function
Azzi Abdelmalek
el 7 de Ag. de 2015
Editada: Azzi Abdelmalek
el 7 de Ag. de 2015
A = rand(10)
v = randi(10,1,2)
idx=sub2ind(size(A),v(1),v(2))
A(idx)
If v is nx2 array
idx=sub2ind(size(A),v(:,1),v(:,2))
A(idx)
Categorías
Más información sobre Matrix Indexing en Centro de ayuda y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
