Filter löschen
Filter löschen

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

4 Ansichten (letzte 30 Tage)
Renat
Renat am 1 Dez. 2017
Kommentiert: Renat am 2 Dez. 2017
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.

Akzeptierte Antwort

Guillaume
Guillaume am 1 Dez. 2017
Bearbeitet: Guillaume am 1 Dez. 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 Kommentare
Guillaume
Guillaume am 1 Dez. 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 am 2 Dez. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by