Azzera filtri
Azzera filtri

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

4 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Guillaume
Guillaume il 1 Dic 2017
Modificato: Guillaume il 1 Dic 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 Commenti
Guillaume
Guillaume il 1 Dic 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 il 2 Dic 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by