使用每行列索引的向量提取矩阵元素 [英] Extract matrix elements using a vector of column indices per row

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

问题描述

我有一个MxN矩阵,我想要一个列向量v,使用向量s告诉我矩阵中的每一行我要走哪一列.

I have an MxN matrix and I want a column vector v, using the vector s that tells me for each row in the matrix what column I will take.

这是一个例子:

Matrix =
[  4  13  93  20  42;
  31  18  94  64  02;
   7  44  24  91  15;
  11  20  43  38  31;
  21  42  72  60  99;
  13  81  31  87  50;
  32  22  83  24  04]    

s = [4 4 5 4 4 4 3].'

所需的输出是:

v = [20 64 15 38 60 87 83].'

我想使用表达式

Matrix(:,s)

本来可以,但是没有.有没有不使用for循环分别访问行的解决方案?

would've work but it doesn't. Is there a solution without using for loops to access the rows separately?

推荐答案

这不是很漂亮,并且可能会有更好的解决方案,但是您可以像这样使用函数sub2ind:

It's not pretty, and there might be better solutions, but you can use the function sub2ind like this:

 M(sub2ind(size(M),1:numel(s),s'))

这篇关于使用每行列索引的向量提取矩阵元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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