필터 지우기
필터 지우기

Unable to remove elements from array and I don't know why

조회 수: 2 (최근 30일)
Garrett Higgins
Garrett Higgins 2021년 1월 12일
댓글: Stephen23 2021년 1월 12일
I have been using matlab for a few years but I just am having one of those days and cannot figure out what is going on here. I have two arbitrary arrays, I iterate and take the distance of each point. If that distance is below 10, I want to remove those elements from the array, therefore shortening the array. The error I'm getting is in the asteriks.
************************************
A null assignment can have only one non-colon index.
Error in LoopTesting (line 10)
x(1,i)=[];
***********************************
Please explain to me why this is happening. Thank you!
y = [1 2 3 4 5 6 7 7 8 8 9 9 10 10];
x = [4 5 6 1 2 3 4 5 6 7 8 8 9 10];
xc = 15;
yc = 15;
for i=1:length(x)
d=sqrt(((xc-x(i))^2)+(yc-y(i))^2);
if d < 10
x(1,i)=[];
y(1,i)=[];
end
end
length(x)
length(y)
  댓글 수: 1
Stephen23
Stephen23 2021년 1월 12일
The problem is that once you remove an element the vector is shorter, but your loop still attempts to index into elements that no longer exist (because you have just shortened the vector). To avoid this either:
  • loop over the vectors backwards
  • collect an index (e.g. a logical vector) and remove the elements at once after the loop

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

답변 (1개)

Fangjun Jiang
Fangjun Jiang 2021년 1월 12일
편집: Fangjun Jiang 2021년 1월 12일
Do the loop backward should resolve the problem. I hope you would understand the reason.
for i=length(x):-1:1
Also, better to use x(i)=[] since it is a vector.

카테고리

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

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by