Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

New to MATLAB?

How to correct the assignment Error?

Asked by PRIYANGA

PRIYANGA (view profile)

on 14 Dec 2012

I have to run the K-means clustering program using matlab.

im = imread('D:\lena256.jpg');
k=5; 
%histogram calculation
img_hist = zeros(256,1);
hist_value = zeros(256,1);
for i=1:256
	img_hist(i)=sum(sum(im==(i-1)));    
end

Run above code the following error occurred.

??? In an assignment  A(:) = B, the number of elements in A and B
must be the same.
Error in ==> kmeansclustering at 10
	img_hist(i)=sum(sum(im==(i-1)));
Error in ==> main at 5
[clusters, result_image, clusterized_image] = kmeansclustering(im,k);

How do I solve this problem?

3 Comments

José-Luis

José-Luis (view profile)

on 14 Dec 2012

Please edit your post. It makes it easier for people to understand your question, and shows a modicum of interest on your part.

Your problem is that

 img_hist(i) 

and

 sum(sum(im==(i-1)))

are of different sizes.

Matt J

Matt J (view profile)

on 14 Dec 2012

Incidentally, why not use HISTC to generate the histogram? Why re-invent that wheel with for-loops?

PRIYANGA

PRIYANGA (view profile)

on 14 Dec 2012

ok Sir I have to try.

PRIYANGA

PRIYANGA (view profile)

2 Answers

Answer by José-Luis

José-Luis (view profile)

on 14 Dec 2012
Accepted answer

Try

 img_hist(i)= sum(sum(sum(im==(i-1))));

im might be a three dimensional matrix.

2 Comments

PRIYANGA

PRIYANGA (view profile)

on 14 Dec 2012

Thank You So Much Sir. Its working

José-Luis

José-Luis (view profile)

on 14 Dec 2012

My pleasure, but please edit your posts for clarity in the future.

José-Luis

José-Luis (view profile)

Answer by Jürgen

Jürgen (view profile)

on 14 Dec 2012

Hi,

there is a function: imhist(I) , quite useful for this work, + if you want to calculate the hist by summing for each value 0=>255 you will get a array with a lenght of 256 not 256*256

regards,J

1 Comment

Jürgen

Jürgen (view profile)

on 14 Dec 2012

and indeed the comment of JL above is also a good point: the image could be a (VertRes, HorRes,3) matrix

Jürgen

Jürgen (view profile)

Contact us