Selecting Elements of a Matrix by Indexing with a Vector
1 次查看(过去 30 天)
显示 更早的评论
I have a 100x3 matrix and I'd like to select one element from each row to form a 100x1 vector. Given a vector of 100 indeces between 1-3, how can I obtain this? The code below is what I thought should work, but instead produces a 100x100 matrix (concatenation of each 100x1 vector generated by each value of indx).
A = rand(100,3);
indx = randi([1 3],100,1); % for each row, which column do I want to pull the element from?
B = A(:,indx); % B is 100x100, I want 100x1
0 个评论
采纳的回答
Ameer Hamza
2020-4-23
编辑:Ameer Hamza
2020-4-23
See sub2ind() function.
A = rand(100,3);
indx = randi([1 3],100,1);
idx = sub2ind(size(A), (1:size(A,1)).', indx);
B = A(idx);
2 个评论
Ameer Hamza
2020-4-23
I think sub2ind is the simplest way to do such a thing. Following avoids sub2ind, but I am not sure you can call it straightforward
A = rand(100,3);
indx = randi([1 3],100,1);
ind = (1:size(A,1)).' + (indx-1).*size(A,1);
B = A(ind);
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!