[英]Problems with sub2ind function in Octave
I am new to Octave, so I was reading documentation and I found sub2ind
function.我是 Octave 的新手,所以我在阅读文档时发现sub2ind
function。 I started to test it, but sometimes it works weird or I just don't understand how it must work.我开始对其进行测试,但有时它工作起来很奇怪,或者我只是不明白它必须如何工作。
So this is how subscripts must be converted to linear indices.所以这就是下标必须转换为线性索引的方式。 (Example from documentation) (来自文档的示例)
[(1,1), (1,2), (1,3)] [1, 4, 7]
[(2,1), (2,2), (2,3)] ==> [2, 5, 8]
[(3,1), (3,2), (3,3)] [3, 6, 9]
And this is another example from documentation这是文档中的另一个示例
s1 = [2, 2];
s2 = [1, 3];
ind = sub2ind ([3, 3], s1, s2)
⇒ ind = 2 8
So if we look at the first example the (2, 2) == 5, but second example says [2, 2] == 2. The (1, 3) has different results too.因此,如果我们看第一个示例 (2, 2) == 5,但第二个示例说 [2, 2] == 2。 (1, 3) 也有不同的结果。 Practically It works as the second example shows.实际上它如第二个示例所示。
If I try to use this function with only 1 pair it return the same pair如果我尝试使用只有一对 function 它返回同一对
sub2ind([3, 3], [2, 2])
# ans = [2, 2]
In this test I can't see any relation between input and output在这个测试中,我看不到输入和 output 之间的任何关系
sub2ind([3, 3], [2, 2], [3, 3])
# ans = [8, 8]
Function works this strange(maybe not) way only when it gets 1 pair or when one of pairs is pair kind [x, x](two same values). Function 仅在获得 1 对或其中一对是对类型 [x, x](两个相同的值)时才以这种奇怪的(也许不是)方式工作。
But otherwise it works fine, so this test returns that it should:但除此之外它工作正常,所以这个测试返回它应该:
sub2ind([3, 3], [2, 1], [1, 3])
# ans = [2, 7]
Also it works fine when this variant is used sub2ind (dims, i, j)
.当使用此变体时,它也可以正常工作sub2ind (dims, i, j)
。 How does the function works? function 是如何工作的?
You misunderstand the input format.您误解了输入格式。
Change改变
s1 = [2, 2];
s2 = [1, 3];
ind = sub2ind ([3, 3], s1, s2)
⇒ ind = 2 8
to this:对此:
row = [2, 2]; % x1 and x2
col = [1, 3]; % y1 and y2
ind = sub2ind ([3, 3], row, col)
⇒ ind = 2 8
You have two inputs that you convert to linear indices: [x1, y1] = [2, 1] = 2
and [x2 y2] = [2, 3] = 8
.您有两个输入可以转换为线性索引: [x1, y1] = [2, 1] = 2
和[x2 y2] = [2, 3] = 8
。
This:这个:
sub2ind([3, 3], [2, 2])
# ans = [2, 2]
appears to be equivalent to:似乎等同于:
sub2ind([3, 3], [2, 2], [1, 1])
even though it's not in the documentation.即使它不在文档中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.