Concept of the null operator question

조회 수: 2 (최근 30일)
Evan Bakalars
Evan Bakalars 2021년 3월 4일
편집: John D'Errico 2021년 3월 8일
This is more of a conceputal question that I need help with.
If I have say sampleMatrix=[1,2,3,4,5] and then I type the code sampleMatrix(3)=[], does that make the matrix now look like [1,2,4,5]?
I ask because I want to know if you do the previously mentioned null operator code, does that now make the third element 4, or is 4 still the fourth element?
Thank you and I apologize if it is confusing.
  댓글 수: 2
the cyclist
the cyclist 2021년 3월 4일
편집: the cyclist 2021년 3월 4일
That syntax fully removes the element from the vector. What used to be a length-5 vector is now a length-4 vector. The number 4 is now the 3rd element of that vector,
sampleMatrix = [1 2 3 4 5];
sampleMatrix(3)=[];
idx = find(sampleMatrix==4)
idx = 3
Stephen23
Stephen23 2021년 3월 5일
"...does that make the matrix now look like [1,2,4,5]?"
Yes.

댓글을 달려면 로그인하십시오.

채택된 답변

John D'Errico
John D'Errico 2021년 3월 8일
편집: John D'Errico 2021년 3월 8일
MATLAB does not allow arrays with empty elements. Double precision arrays are always nice rectangular things. So, for example, the array
[1 2 3 [] 5 6]
ans = 1×5
1 2 3 5 6
is just a vector with 5 elements. The 4th element there is the number 5.
Similarly, you cannot insert an "empty" cell into a vector.
Therefore, the syntax in MATLAB to delete an element of a vector is to set it equal to [], empty brackets.
V = 1:5;
V(4) = []
V = 1×4
1 2 3 5
Again, the result is a vector of length 4. Everything to the right of that element gets shuffled over.
You can use [] to delete multiple elements at once, thus
V = 1:10;
V(2:2:end) = []
V = 1×5
1 3 5 7 9
And, for example, the third element of the new vector V is just 5.
V(3)
ans = 5
All of that said, you need to be careful when working with cell arrays, because cell arrays CAN contain empty cells. But for regular flat arrays, [] is just the tool to delete elements.

추가 답변 (1개)

Prudhvi Peddagoni
Prudhvi Peddagoni 2021년 3월 8일
Hi,
As seen in this answer , it does remove the 3rd element.
Hope this helps.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by