Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

How can I dynamically assign/access elements in a matrix with arbitrary dimensions?

Asked by Erling Hugo Jensen on 15 Jan 2013
Latest activity Commented on by Matt about 13 hours ago

I am creating a code to manipulate a matrix generated from an external file. I would like to make it so that the matrix could have arbitrary dimensions, e.g. in one file it might be just one dimension so listing all the elements could be done like:


in another, it might have two dimensions, so listing the elements could be done like:


if three,


and so on. My problem is that I don’t know how (or maybe it is not possible) to make some general code to manipulate the matrix A. If I had know that A had dimension 3, I could just do something like


But what I would like to do is something like


where C is a list equal to [n m o] or [n m o … z].

Any ideas?



Erling Hugo Jensen


No products are associated with this question.

2 Answers

Answer by Jan Simon on 15 Jan 2013
Edited by Jan Simon on 31 Jul 2013

Not matching the question exactly, but worth to mention:

A = rand(2,3,4)   % Or: rand(2,3,4,5,4,3,2)
Index    = cell(1, ndims(A));
Index(:) = {:};   % BUGFIX: {':'} was meant, thanks Walter and Jim
A(Index{:})   % Equivalent to: A(:, :, :)
Index{2} = 2:3;


Jim Hokanson on 17 Sep 2013


   Thanks for the pointer on flags. Any other suggestion on how to mark something as needing to be fixed without having sufficient 'reputation' to fix it?
Jan Simon on 17 Sep 2013

@Jim: You can post a comment. Comments are a standard method in human communication to point out a specific detail.

But flags are used such rarely, that the forum does not suffer from a "misused" flag.

Matt about 13 hours ago

Sharp! thanks

Jan Simon
Answer by José-Luis on 15 Jan 2013
Edited by José-Luis on 15 Jan 2013

You could reference values by their linear index. If you don't want to use sub2ind(), then you can always compute it yourself:

your_mat = rand(3,3,3) %some example
numDim = ndims(your_mat);
your_size = nan(1,numDim);
for ii = 1:numDim;
    your_size(ii) = size(your_mat,ii);
your_idx = [2 2 2];
tot = your_idx(1); %linear index from the sub-index vector
for ii = numDim:-1:2
    tot = tot  + (your_idx(ii)-1) .* prod(your_size(1:ii-1));
your_val = your_mat(tot) 



Contact us