MATLAB: Undefined function or variable in tracking green ball example

ball trackingcolor based trackingcolor segmentationimage processingImage Processing Toolboxobject tracking

I'm attempting to follow the tracking a green ball example found here:
using my built in webcam. When I attempt to run the code I am getting an error undefined function or variable bwbw. I am using the following code for the trackball function:
function [img, bw] = trackball(img, thresh)
r = img(:, :, 1);
g = img(:, :, 2);
b = img(:, :, 3);
justGreen = g - r/2 - b/2;
bw = justGreen > thresh;
[x, y] = find(bw);
if ~isempty(x) && ~isempty(y)
xm = round(mean(x));
ym = round(mean(y));
xx = max(1, xm-5):min(xm+5, size(bw, 1));
yy = max(1, ym-5):min(ym+5, size(bw, 2));
bwbw = zeros(size(bw), 'uint8');
bwbw(xx, yy) = 255;
end
imagesc(justGreen + bwbw);
and am calling it using this code (I've tried running it both from the command window and by creating a script and running it):
function [img, bw] = trackball(img, thresh)
r = img(:, :, 1);
g = img(:, :, 2);
b = img(:, :, 3);
justGreen = g - r/2 - b/2;
bw = justGreen > thresh;
[x, y] = find(bw);
if ~isempty(x) && ~isempty(y)
xm = round(mean(x));
ym = round(mean(y));
xx = max(1, xm-5):min(xm+5, size(bw, 1));
yy = max(1, ym-5):min(ym+5, size(bw, 2));
bwbw = zeros(size(bw), 'uint8');
bwbw(xx, yy) = 255;
end
imagesc(justGreen + bwbw);
I was able to run it successfully once last week without obtaining this error, but now I cannot fix it. I do make sure to create a camera object (using cam = webcam) before I run the loop that captures the snapshots. Any help would be greatly appreciated. Thanks!

Best Answer

This poorly written code never assigns bwbw in the case where no green is found. To fix, add this line after you threshold it to find bw:
bwbw = zeros(size(bw), 'uint8');
Even better, use my code instead. It's attached.