필터 지우기
필터 지우기

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

조회 수: 4 (최근 30일)
Renat
Renat 2017년 12월 1일
댓글: Renat 2017년 12월 2일
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