Index of element to remove exceeds matrix dimensions.

4 次查看(过去 30 天)
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
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