在矩阵下标和线性索引之间进行转换(如Matlab中的ind2sub/sub2ind) [英] Converting between matrix subscripts and linear indices (like ind2sub/sub2ind in matlab)

查看:100
本文介绍了在矩阵下标和线性索引之间进行转换(如Matlab中的ind2sub/sub2ind)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个矩阵

m <- matrix(1:25*2, nrow = 5, ncol=5)

如何从矩阵下标(行索引,列索引)变为可以在矩阵上使用的线性索引.例如,您可以使用这两种方法之一提取矩阵的值

How do you go from matrix subscripts (row index, column index) to a linear index you can use on the matrix. For example you can extract values of the matrix with either of these two methods

m[2,3] == 24
m[12] == 24

您如何从(2,3)=>12或12 =>(2,3)在R

How do you go from (2,3) => 12 or 12 => (2,3) in R

在Matlab中,用于将矩阵下标转换为线性索引,反之亦然的函数是 ind2sub 和`sub2ind

In Matlab the functions you would use for converting matrix subscripts to linear indices and vice versa are ind2sub and `sub2ind

R中有等效的方法吗?

Is there an equivalent way in R?

推荐答案

这不是我以前使用过的东西,但是根据

This is not something I've used before, but according to this handy dandy Matlab to R cheat sheet, you might try something like this, where m is the number of rows in the matrix, r and c are row and column numbers respectively, and ind the linear index:

MATLAB:

[r,c] = ind2sub(size(A), ind)

R:

r = ((ind-1) %% m) + 1
c = floor((ind-1) / m) + 1

MATLAB:

ind = sub2ind(size(A), r, c)

R:

ind = (c-1)*m + r

这篇关于在矩阵下标和线性索引之间进行转换(如Matlab中的ind2sub/sub2ind)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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