error in matlab, cellfun, display image

조회 수: 15 (최근 30일)
Tomas
Tomas 2014년 4월 26일
답변: sanidhyak 2025년 2월 3일
Hello, i have a problem with cellfun
my code:
Z = cellfun(@(Z) Z', Z,'Un',0);
Z = cellfun(@(Z) cell2mat(Z), Z,'Un',0);
Z = cellfun(@(Z) sub2ind(size(I) , Z(:,1) , Z(:,2)), Z,'Un',0);
figure;
cluster = zeros(size(I));
for ii = 1:length(Z)
cluster(Z{ii}) = ii;
end
imshow(label2rgb(cluster))
title('Vystupny obraz - Metoda KMEANS','FontSize',16,'Color','k');
error:
??? Attempted to access Z(:,2); index out of bounds because size(Z)=[952,1].
Error in ==> KMNSimage>@(Z)sub2ind(size(I),Z(:,1),Z(:,2)) at 503
Z = cellfun(@(Z) sub2ind(size(I) , Z(:,1) , Z(:,2)), Z,'Un',0);
Error in ==> KMNSimage at 503
Z = cellfun(@(Z) sub2ind(size(I) , Z(:,1) , Z(:,2)), Z,'Un',0);
Z is :
Z={1x952 cell} {1x3141 cell} {1x3141 cell} {1x3141 cell}
know someone help ?
Thanks.

답변 (1개)

sanidhyak
sanidhyak 2025년 2월 3일
Hi Tomas,
Based on my understanding the issue you are facing is an "index out of bounds" error when attempting to access “Z(:,2)” in the code provided.
I am assuming the following initialization, as it is not explicitly mentioned:
imageHeight = 512;
imageWidth = 512;
I = uint8(rand(imageHeight, imageWidth) * 255);
When running the code provided by you, I too faced a similar error:
Index in position 2 exceeds array bounds.
Error in test1>@(Z)sub2ind(size(I),Z(:,1),Z(:,2)) (line 26)
Z = cellfun(@(Z) sub2ind(size(I) , Z(:,1) , Z(:,2)), Z,'Un',0);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This error occurs because some elements of Z are 1xN cell arrays instead of Nx2 matrices, which causes the indexing Z(:,2) to fail. To fix this, please ensure that each element of Z is correctly converted into an Nx2 matrix before calling “sub2ind.
Kindly refer to the following corrected code:
Z = cellfun(@(Z) Z', Z, 'UniformOutput', false); % Transpose each cell element
Z = cellfun(@(Z) cell2mat(Z), Z, 'UniformOutput', false); % Convert to matrix
% Ensure each matrix has two columns before applying sub2ind
Z = cellfun(@(Z) reshape(Z, [], 2), Z, 'UniformOutput', false);
Z = cellfun(@(Z) sub2ind(size(I), Z(:,1), Z(:,2)), Z, 'UniformOutput', false);
% Create output cluster map
cluster = zeros(size(I));
for ii = 1:length(Z)
cluster(Z{ii}) = ii;
end
imshow(label2rgb(cluster));
title('Vystupny obraz - Metoda KMEANS', 'FontSize', 16, 'Color', 'k');
Here, “reshape(Z, [], 2) makes sure that the contents of each cell are formatted into two columns correctly, which helps avoid any indexing problems.
To learn more about this, kindly refer to the following documentations:
Cheers and happy coding :)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by