Reputation: 422
I'm trying to assign some values to a matrix.In the case of 2 or 3 dimension, it is easy to use sub2ind. However the data I use has 23 dimensions. The situation could be explained better with an example. A
is a matrix which has 3x4x5x6x7
dimensions. I want to assign something to A(1,2,3,4,5)
with linear indexing. Normally, it is possible with sub2ind like:
A(sub2ind(siz,1,2,3,4,5)) = any_var;
However the thing I want is that assigning the sub2ind input with an array instead of commas. Is there anything which satisfies this in MATLAB?
A(sub2ind(siz,[1 2 3 4 5])) = any_var; % I want something like this.
Upvotes: 2
Views: 125
Reputation: 112679
Define the vector with the index values
x = [1 2 3 4 5];
Then you can convert to cell (using num2cell
) and from that to a comma-separated list:
xc = num2cell(x);
A(sub2ind(siz, xc{:})) = any_var;
Or you could do the computation directly and avoid sub2ind
. To convert to linear index, subtract 1 from the index along the k-th dimension and multiply by the cumulative product of the sizes of the preceding dimensions. The sum for all k plus 1 is the linear index:
A(x(1) + sum((x(2:end)-1).*cumprod(siz(1:end-1)))) = any_var;
Upvotes: 5