Why is Matlab showing "Index exceeds matrix sizes"?
Here is my matlab code:
gg=imread('fsu_Westcott.jpg'); data1=gg(:,1); histArray1=zeros(1,256); x=0:1:255; for n=1:length(data1) histArray1(1,data1(n)+1)=histArray1(1,data1(n)+1)+1; end for n=1:length(data1) number1=sum(histArray1(1:n)); end plot(x,number1,'r')
Why does it show "Index exceeds matrix size"? before I finally speak? I'm a beginner and thanks in advance! :)
source to share
It seems to me that you have a couple of things that you want to fix. To fix the error on the line Simon pointed out, I think you want your second loop to For
go from 1 to length(histArray)
(or 256) instead length(data1)
. The second problem I see is that in the second loop For
you are not creating the array - you are just redefining the variable number1
over and over. You should probably put number1(n)=sum(histArray1(1:n));
inside to use a loop instead. This is not related to the error you are seeing, but may help you get what you want from the script.
source to share
In line:
number1=sum(histArray1(1:n));
you are asking for cells 1 to an n
array histArray1
, but n
goes from 1 to length(data1)
which is greater than the length histArray1
(256). So it's over the edge.
This loop:
for n=1:length(data1)
number1=sum(histArray1(1:n));
end
seems unnecessary if you want to plot a histogram anyway.
Another tip, there is a function called hist
that you could use to calculate a histogram and plot a bar chart in one line:
hist(data1(:), 0:255)
source to share