How can I create a variable for subscripts of an array?

11 views (last 30 days)
Hello all,
I want to create and use a single variable for subscript range of a multi-dimensional array. I know for a 1D-array I can do:
array=ones(20,1);
indices=5:10;
array(indices)=0;
I tried something like this for a 3D-array, but it didnt work:
array=ones(10,10,10);
indices=[2:5,3:6,4:7];
array(indices)=0;
but it didnt work. Is it possible to create a variable that I can use in such manner? Thank you.

Accepted Answer

Guillaume
Guillaume on 1 Dec 2017
Edited: Guillaume on 1 Dec 2017
You need to convert your subscript indices into linear indices. You do that with sub2ind:
array(sub2ind(size(array), indices)) = 0;
edit: completely misread the question. The above is completely wrong. See discussion in the comments. The correct answer should have been:
indices = {2:5, 3:6, 4:7};
array(indices{:}) = 0;
  3 Comments
Guillaume
Guillaume on 1 Dec 2017
"It doesnt work"
Then don't accept the answer!
Of course, it doesn't work. I completely misread the question.
The main problem with your question is that it is flawed. You try to define indices as:
indices=[2:5,3:6,4:7]
The problem is that the above array is exactly the same as:
indices = [2:4, 5:-2:3, 4, 5:6, 4:7]
or
indices = [2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7]
i.e. your distinction between the three ranges doesn't really exist. It's all concatenated into one vector
Now, to answer your question properly:
You need to define your dimension indices as a cell array
array = reshape(1:1000, 10, 10, 10);
indices = {2:5, 3:6, 4:7} %notice how it's all three separate vectors
Using indices is then easy:
array(indices{:}) = 0
Renat
Renat on 2 Dec 2017
Well, I could unaccept, but your answer pushed me in the right direction of using linear indices and it worked in the end.
I didn't imply that my original way of assigning indices was correct. That was what first came to mind. I was looking for proper syntax of doing it. Thank you. This is a more efficient way of doing it.

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!