how to avoid index out of bounds error

13 Ansichten (letzte 30 Tage)
ravi
ravi am 11 Apr. 2014
Beantwortet: Ken Atwell am 12 Apr. 2014
hi,I am trying excute fallowing programme,but it is showing Attempted to access proj(2); index out of bounds because numel(proj)=1 error.I was not able to solve this problem.anybody know answer suggest me.thanks in advance.
I = imread('ch_text.tiff');
[row ,col]=size(I);
h_proj=zeros;
for i = 1:row
sum=0;
for j=1:col
if I(i,j)==0 %black pixel found
sum=sum+1;
end
end
h_proj(i)=sum;
end
figure,plot(h_proj,1:row),title('horizontal projection');
nonzero_row_indx=zeros;
i = 1; k = 1;
while (i >= 1) && (i <= row)
if h_proj(i) ~= 0
nonzero_row_indx(k) = i;
k = k + 1;
i = i + 1;
while h_proj(i) ~= 0
i = i + 1;
end
nonzero_row_indx(k) = i - 1;
k = k + 1;
end
i = i + 1;
end
  1 Kommentar
Walter Roberson
Walter Roberson am 12 Apr. 2014
Your code does not have a variable named "proj"

Melden Sie sich an, um zu kommentieren.

Antworten (3)

Nitin
Nitin am 12 Apr. 2014
I tried running your programme using the Matlab built-in image, blobs.png and received the following error:
Attempted to access h_proj(273); index out of bounds because numel(h_proj)=272.
It would appear that the way you are incrementing i is not the correct, not sure what you are trying to achieve but i is getting incremented more than it should be in your code, hence the out of bounds error

Walter Roberson
Walter Roberson am 12 Apr. 2014
Your code
while h_proj(i) ~= 0
i = i + 1;
end
is going to fail if h_proj ends with non-zero.
Note: do not name a variable "sum" as that will interfere with use of the important MATLAB routine sum()

Ken Atwell
Ken Atwell am 12 Apr. 2014
Your inner-most 'while' loop continues to increment 'i' while 'h_proj(i)' is nonzero. This will fall out of bounds if the last value of 'h_proj(i)' is nonzero.
As you learn more about MATLAB, I encourage you to learn more about MATLAB's vector syntax, which can help you avoid overruns like this. As currently written, your code looks like an almost-direct port of something a C programmer would write. For example, the doubly-nested loop that sums black pixels can be done in a single instruction:
h_proj = sum(I==0,2)';
Have fun.

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by