フィルターのクリア

Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Matrix dimension must agree error in the code,need a solution

1 回表示 (過去 30 日間)
Poonam
Poonam 2013 年 9 月 23 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
function [clusters, result_image, clusterized_image] = kmeanssegment(im,k)
%histogram calculation
hist_value = zeros(256,1);
img_hist = zeros(1,256); % Reset
tic
[rows, columns] = size(im);
for col = 1 : columns
for row = 1 : rows
img_hist(im(row,col)+1) = img_hist(im(row,col)+1) + 1;
end
end
toc
for i=1:256
hist_value(i)=i-1; %#ok<NASGU>
end
%cluster initialization
cluster=zeros(k,1);
cluster_count = zeros(k,1);
for i=1:k
cluster(i)=uint8(rand*255);
end;
old = zeros(k,1);
while (sum(sum(abs(old-cluster))) >k)
old = cluster;
closest_cluster = zeros(256,1);
min_distance = uint8(zeros(256,1)); %#ok<NASGU>
min_distance = abs(hist_value-cluster(1));
%calculate the minimum distance to a cluster
for i=2:k
min_distance =min(min_distance, abs(hist_value-cluster(i)));
end;
%calculate the closest cluster
for i=1:k
closest_cluster(min_distance==(abs(hist_value-cluster(i)))) = i;
end
%calculate the cluster count
for i=1:k
cluster_count(i) = sum(img_hist.*(closest_cluster==i));
end;
for i=1:k
if (cluster_count(i) == 0)
cluster(i) = uint8(rand*255);
else
cluster(i) = uint8(sum(img_hist(closest_cluster==i).*hist_value(closest_cluster==i))/cluster_count(i));
end
end
end
imresult=uint8(zeros(size(im)));
for i=1:256
imresult(im==(i-1))=cluster(closest_cluster(i));
end;
clustersresult=uint8(zeros(size(im)));
for i=1:256
clustersresult(im==(i-1))=closest_cluster(i);
end;
clusters = cluster;
result_image = imresult;
clusterized_image = clustersresult;
end
Error Elapsed time is 0.008945 seconds. ??? Error using ==> times Matrix dimensions must agree.
Error in ==> kmeansclustering at 52 cluster(i) = uint8(sum(img_hist(closest_cluster==i).*hist_value(closest_cluster==i))/cluster_count(i));
Error in ==> kmeansclusteringdemo at 82 k=kmeansclustering(im,5);

回答 (1 件)

Image Analyst
Image Analyst 2013 年 9 月 23 日
編集済み: Image Analyst 2013 年 9 月 23 日
Standard debugging technique is to break up the long expressions into smaller parts and look at them, so
sum(img_hist(closest_cluster==i).*hist_value(closest_cluster==i))
becomes
a=img_hist(closest_cluster==i)
whos a
b = hist_value(closest_cluster==i)
whos b
c = sum(a.*b)
whos c
Give that a try and see what you learn. a and b should be the same size to do the element by element multiplication. But they won't be - that's why you got the error.

この質問は閉じられています。

Community Treasure Hunt

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

Start Hunting!

Translated by