Index of element to remove exceeds matrix dimensions.

조회 수: 7 (최근 30일)
Prasanna Venkatesh
Prasanna Venkatesh 2016년 3월 2일
편집: Prasanna Venkatesh 2016년 3월 2일
In my code x tends to change from 1 to 7. Here I took a sample value as 4. I want to delete the array element, if it has less than 0 or greater than 8 otherwise save the value in the array. xplus is an 1-D array. xplus maximum value will be 7 values. I tried this code it is getting error as
ERROR: Index of element to remove exceeds matrix dimensions.
Error in deletearraytest (line 5) xplus(x1)=[];
and workspace variable x=4 , x1=7, xplus=[5;6;7;8;0]
Here is my code x=4; xplus=zeros(7,1); for x1=1:7 if((x+x1<=0)||(x+x1>8)) xplus(x1)=[]; else xplus(x1)=x+x1; end end
I have check the solutions of many links but, I cant understand the mistake I did. Many people said that when we are going to delete the array element, it not going to be previous size. I need more explanation in that and solve my problem. I am amateur matlab user. Help needed. Thanks in advance.

채택된 답변

Kevin Claytor
Kevin Claytor 2016년 3월 2일
편집: Kevin Claytor 2016년 3월 2일
Because you're removing elements as you go, your array gets shorter, and your fixed index (1:7) can go out of bounds.
This is exactly what is happening when you have:
x1=7, xplus=[5;6;7;8;0]; xplus(x1)=[];
You're trying to remove the 7th element, when the array only has 5 elements in it.
A better way of accomplishing what you're doing is with logical indexing;
xplus(xplus < 0 | xplus > 8) = [];
which finds the elements of x < 0 or > 8 and removes them.
  댓글 수: 1
Prasanna Venkatesh
Prasanna Venkatesh 2016년 3월 2일
편집: Prasanna Venkatesh 2016년 3월 2일
Thank you so much,it worked. I was over this error for weeks and cant understand the concept also.

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

추가 답변 (0개)

카테고리

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