向量作为矩阵中的列索引 [英] Vector as column index in matrix

查看:80
本文介绍了向量作为矩阵中的列索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个矩阵A(mxn)和一个向量B(mx1),我想创建一个向量C(mx1),其中每个行元素都是<B索引的列中的c0>.
不用循环就可以做到吗?

Given a matrix A (mxn) and a vector B (mx1) I want to create a vector C (mx1) in which each row element is the row element of A from a column indexed by B.
Is it possible to do this, without using loops?

A = [1 2; 3 4; 5 6];
B = [2 1 1].';

然后我想要:

C = [2 3 5].';

推荐答案

B的列下标转换为线性索引,然后使用它们来引用A中的元素:

Convert the column subscripts of B to linear indices and then use them to reference elements in A:

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

(有关更多信息,请阅读此答案中的有关线性索引的部分).

(for more information, read the part about linear indexing in this answer).

这篇关于向量作为矩阵中的列索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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