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

조회 수: 1 (최근 30일)
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)

채택된 답변

Rik
Rik 2019년 10월 14일
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))

추가 답변 (1개)

Andrei Bobrov
Andrei Bobrov 2019년 10월 14일
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

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by