Variable-Length Array Addressing in Matlab
I'm sure there's an easy answer to this, but I'm not really sure what to search for. I have an array, M, of D dimensions, where D is constrained to be 1 <= D <= 5, and a vector of length D, X. I'd like to use D as an开发者_StackOverflow address within M and increment the value at that address, so if D were [1 2 3]
, I would want to increment M(1,2,3)
. I know I can do it like so:
if D == 1
M(X(1)) = M(X(1)) + 1;
end
if D == 2
M(X(1), X(2)) = M(X(1), X(2)) + 1;
end
But it's really ugly and I have to imagine there's a simpler, less clumsy way. Thanks!
You can use the function sub2ind
to convert the address vector D
to the corresponding dimensions in M
. However, this would require that you store D
as a cell and not a vector. The following example should help.
A=magic(5);%# just a test matrix
A=
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
d={3,4};%we need the element at row 3, column 4
indx=sub2ind(size(A),d{:});%# get the index corresponding to the subscript 3,4
A(indx)
ans=
20
You can also directly index it into the matrix A
as A(sub2ind(size(A),d{:}))
, without having to create a separate variable.
You can also use num2cell
to convert the vector to a cell. This might be a better option, as you might want to store D
as a vector for other purposes. So the corresponding line becomes
indx=sub2ind(size(A),num2cell(d));
精彩评论