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)
0 个评论
采纳的回答
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))
0 个评论
更多回答(1 个)
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Operating on Diagonal Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!