在每一行中获取不同的列 [英] Get different column in each row

查看:101
本文介绍了在每一行中获取不同的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从矩阵的每一行中获取不同的列.例如:

I would like to get a different column out of each row from a matrix. For example:

A = [1,2;1,4;5,2]
B = [2;2;1]

输出应产生:

out = [2;4;5]

因此,简而言之:A是矩阵,而B具有每行列的索引.如何在不使用循环的情况下做到这一点(如果可能)?

So in short: A is the matrix and B has the indices for the colums per row. How can I do this without using a loop (if it's possible)?

推荐答案

您可以使用 sub2ind 将(i,j)索引转换为矩阵A中的线性索引

You can use sub2ind to convert (i,j) indices to linear indices in matrix A

idx = sub2ind(size(A), 1:size(A, 1), B');
A(idx)

ans =

 2     4     5

假设向量B的条目与A中的行一样多,这是可行的.在上面的sub2ind中,为每对随后的行号(1:size(A,1))和列中给出的列号生成线性索引B.

That works assuming that vector B has as many entries as there are rows in A. In the above sub2ind generates a linear index for every pair of subsequent row numbers (1:size(A, 1)) and column numbers given in B.

这篇关于在每一行中获取不同的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆