MATLAB: Error “Assignment has more non-singleton rhs dimensions than non-singleton subscripts” happened

arrayimage processing

I want to get rgb color and to put it in another image at accordance pixel
And shows " error B(i,j,:)=I(i,j,:)";
This is source code:
I=imread('peppers.jpg');
imshow(I);
R=imrect;
p=R.getPosition;
[J,map] = rgb2ind(I,1024);
hr = imhist(J(p(2):p(2)+p(4)-1,p(1):p(1)+p(3)-1),map);
[height,width,~]=size(I);
B=zeros(height,width);
for i=1:height
for j=1:width
if hr(J(i,j)+1)>0
B(i,j,:)=I(i,j,:);
end
end
end
imshow(B);
but, when B(i,j,:)=true; it works; but, I dont need white color, need rgb color

Best Answer

Change
[height,width,~]=size(I);
B=zeros(height,width);
to
[height,width,panes]=size(I);
B=zeros(height,width,panes);