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

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

问题描述

考虑矩阵 M 以及存储在 I J 列中的一组下标。我需要访问由I& A指定的元素。 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];

此外,由于I& 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天全站免登陆