在 Matlab 中挑选给定指定列的矩阵条目,无需 for 循环

发布于 2024-12-09 06:25:20 字数 809 浏览 0 评论 0原文

可能的重复:
MATLAB 索引问题
如何在Matlab中从矩阵中提取非垂直列< /a>

我觉得应该有一个简单的方法来做我想做的事,但我无法弄清楚这一点。

输入:一个 nx t 实数矩阵 M 和一个 nx 1 向量 I索引

OUTPUT:一个 nx 1 向量 P,使得 P(i) = M( i, I(i) )< /code>

很明显如何使用for 循环,但这是 Matlab,并且 n 很大。有没有办法向量化这个问题并避免 for 循环?

Possible Duplicate:
MATLAB indexing question
How to extract non-vertical column from matrix in Matlab

I feel like there should be a simple way to do what I want, but I cannot figure this out.

INPUT: an n x t matrix M of reals and an n x 1 vector I of indices

OUTPUT: an n x 1 vector P such that P(i) = M( i, I(i) )

It's obvious how to do this with a for loop, but this is Matlab and n is large. Is there a way to vectorize this problem and avoid the for loop?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

要走干脆点 2024-12-16 06:25:20

这是使用线性索引的简单、快速、矢量化解决方案。

indx = (1:n)' + (I-1)*n; %'
P=M(indx);

例子:

M = randi(10,[3,4]);     %# test matrix

M =

     9    10     3    10
    10     7     6     2
     2     1    10    10

n = size(M,1);
I = [3,1,4]';            %'# index vector
indx = (1:n)' + (I-1)*n; %'
P = M(indx)

P =

 3
10
10

Here's a simple, fast, vectorized solution using linear indexing.

indx = (1:n)' + (I-1)*n; %'
P=M(indx);

Example:

M = randi(10,[3,4]);     %# test matrix

M =

     9    10     3    10
    10     7     6     2
     2     1    10    10

n = size(M,1);
I = [3,1,4]';            %'# index vector
indx = (1:n)' + (I-1)*n; %'
P = M(indx)

P =

 3
10
10
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文