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 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
sub2indto convert the address vectorDto the corresponding dimensions inM. However, this would require that you storeDas a cell and not a vector. The following example should help.You can also directly index it into the matrix
AasA(sub2ind(size(A),d{:})), without having to create a separate variable.You can also use
num2cellto convert the vector to a cell. This might be a better option, as you might want to storeDas a vector for other purposes. So the corresponding line becomes