使用下标访问值而不使用 sub2ind [英] Accessing values using subscripts without using sub2ind

查看:25
本文介绍了使用下标访问值而不使用 sub2ind的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个矩阵 M 和一组存储在 IJ 列中的下标.我需要访问 I & 指定的元素J 而不将它们转换为线性索引(即使用 sub2ind).例如

Consider a matrix M and a set of subscripts stored in columns I and J. I need to access the elements designated by I & J without converting them to linear indices (i.e. using sub2ind). E.g.

M = [1 2 3;4 5 6;7 8 9];
I = [1 1 1];
J = [1 2 3];

VALS = [1 2 3];

此外,执行以下操作是不可行的,因为我 &J 巨大:

Also, doing the following is not feasible since I & J are huge :

VALS = diag(M(I,J));

为了演示,这不是我要找的,

And for demonstration, this is not what I'm looking for,

VALS = M(sub2ind(size(M),I,J));

基本上 sub2ind 似乎花费了很多时间,现在我正在寻找方法来访问这些元素而不将下标转换为索引.只要比使用 sub2ind 的方法更快,任何其他方法都是可行的.

Essentially sub2ind seems to be taking a lot of time and right now I'm looking for methods to access these elements without converting the subscripts to indices. Any other way is feasible as long as it's faster than the method using sub2ind.

推荐答案

可能比使用 SUB2IND 更快:

This may be faster than using SUB2IND:

[r,c] = size(M);  % Get the size of M
vals = M(I+r.*(J-1));  % Compute a linear index with vector operations

这篇关于使用下标访问值而不使用 sub2ind的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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