答案 0 :(得分:0)
你的例子不起作用。您正在为第二个元素编制索引两次(顺便说一句,floor (rand (n) * x)
的一个不错的替代方法是使用randi()
):
octave> M = randi(10, 3)
M =
9 2 5
9 3 1
2 8 7
octave> v = [2;2];
octave> M(v)
ans =
9
9
octave> M([2;2])
ans =
9
9
执行所需操作的正确方法是使用适用于任意维度的sub2ind()
。
octave> M(sub2ind (size (M), 2, 2))
ans = 3
octave> M = randi (10, 3, 3, 3)
M =
ans(:,:,1) =
6 3 10
1 7 9
7 6 8
ans(:,:,2) =
7 9 10
9 4 5
8 5 5
ans(:,:,3) =
3 5 10
8 3 10
4 9 4
octave> M(sub2ind (size (M), 1, 2, 3))
ans = 5
答案 1 :(得分:0)
我编辑了sub2ind函数,因此可以使用向量。
的工作原理如下:
M(sub2ind2(dims, V));
我可能会在接下来的几天发送修改后的sub2ind2函数。
[编辑]
function ind = sub2ind2 (dims, varargin)
if (nargin > 1)
if (isvector (dims) && all (round (dims) == dims))
nd = length (dims);
v = varargin{1};
vlen = length (v)
dims(vlen) = prod (dims(vlen:nd));
dims(vlen+1:nd) = [];
scale = cumprod (dims(:));
for i = 1:vlen
arg = v(i);
if (isnumeric (arg) && isequal (round (arg), arg))
if (i == 1)
if (all (arg(:) > 0 & arg(:) <= dims(i)))
ind = first_arg = arg;
else
error ("sub2ind: index out of range");
endif
else
if (size_equal (first_arg, arg))
if ((i > nd && arg == 1) || all (arg(:) > 0 & arg(:) <= dims(i)))
ind += scale(i-1) * (arg - 1);
else
error ("sub2ind: index out of range");
endif
else
error ("sub2ind: all index arguments must be the same size");
endif
endif
else
error ("sub2ind: expecting integer-valued index arguments");
endif
endfor
else
error ("sub2ind: expecting dims to be an integer vector");
endif
else
print_usage ();
endif
endfunction