Return a vector with the same size as the indexing matrix/vector (code optimization)

1 view (last 30 days)
I have the following problem:
I would like to access elements inside a vector (in this case, a vector column) and avoid the use of any loops.
The output of the vector can have a different ordering, given the values of the index matrix.
When i have a vector column like
V=[20;10;13] , then the size is (size(), m=3,n=1)
Therefore, when i access it with a matrix like index = [1 3;2 1]
V(index) returns a matrix of (size(),m=2,n=2)
Nevertheless, when the index is a matrix with a single row (or row vector), the output is a column vector (instead of the desired row vector)
index = [1 3]
V(index) returns a matrix of (size(),m=2,n=1) instead of returning the desired (size(),m=1,n=2)
Anyone knows how I could solve this? (My software could have an index matrix with 1 or more rows)

Accepted Answer

Rik
Rik on 14 Oct 2019
I would have expected Matlab to have consistent behavior, but before now I hadn't bothered to look it up in the documentation. You can revert a possible flip by using reshape:
V=[20;10;13];
index=[1 3;2 1];
out=reshape(V(index),size(index))

More Answers (1)

Andrei Bobrov
Andrei Bobrov on 14 Oct 2019
General case:
out = reshape(V(index),size(index));
For your case V - vector (n x 1):
if size(index,1) == 1
out = V(index)';
else
out = V(index);
end

Categories

Find more on Operating on Diagonal Matrices 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!