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

4 次查看(过去 30 天)
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.

采纳的回答

Guillaume
Guillaume 2017-12-1
编辑:Guillaume 2017-12-1
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 个评论
Guillaume
Guillaume 2017-12-1
"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 2017-12-2
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by