MATLAB: How to colour columns of a matrix

colour matrix

I'm trying to create a 2D Colour Barcode. Different columns of the matrix will have different colours. I'm unable to get the desired output. Please help me solving it. The colour of the last letter overlaps with the first column. The matrix is a 1024×1024 matrix.
a=(get(handles.inp,'string'));
b=numel(a); %string length
c=1024/b; %dividing barcode into equal no. of columns (letters)
redChannel = zeros(1024, 1024, 'uint8');
greenChannel = zeros(1024, 1024, 'uint8');
blueChannel = zeros(1024, 1024, 'uint8');
for i=1:b
j=1:c:1024;
if(a(i)=='A')
redChannel(1:1024,j:j+c)=255; %red colour for letter A
greenChannel(1:1024,j:j+c)=0;
blueChannel(1:1024,j:j+c)=0;
%j=j+c+1;



elseif(a(i)=='B')
redChannel(1:1024,j:j+c)=0;
greenChannel(1:1024,j:j+c)=255; %green colour for letter B
blueChannel(1:1024,j:j+c)=0;
%j=j+c+1;
elseif(a(i)=='C')
redChannel(1:1024,j:j+c)=255; %yellow colour for letter C
greenChannel(1:1024,j:j+c)=255;
blueChannel(1:1024,j:j+c)=0;
%j=j+c+1;
elseif(a(i)=='D')
redChannel(1:1024,j:j+c)=0;
greenChannel(1:1024,j:j+c)=0;
blueChannel(1:1024,j:j+c)=255; %blue colour for letter D
%j=j+c+1;
end
end
coloredImage = cat(3, redChannel, greenChannel, blueChannel);
imshow(coloredImage)

Best Answer

The first problem with your code is that you're assuming c is integer when it will most likely not be.
In any case, the whole loop and the bunch of if/elseif is not the way you should write code in matlab. This can all be done more simply:
inputstring = get(handles.inp,'string'); %don't use unnecessary brackets. And use meaningful names for your variables
letters = 'ABCD';
lettercolours = uint8([255, 0, 0; ...for A
0, 255, 0; ...for B
255, 255, 0; ...for C
0, 0, 255]); %for D
[found, whichrow] = ismember(inputstring, letters); %find which colour goes with each letter of the input
assert(all(found), 'Some letters in input are not valid');
letterswidth = diff(round(linspace(0, 1024, numel(inputstring)+1))); %compute width of each letter colour patch. There's probaby a simpler way. Ensure width is integer
colouredimage = repelem(permute(lettercolours(whichrow, :), [3 1 2]), 1024, letterswidth, 1); %replicate each colour patch according to calculate width and a 1024 height.
imshow(colouredimage);
The above is also a lot easier to extend than a bunch of elseif. You want to support more letters, simply add them to the letters variable and add the corresponding colours as rows of lettercolours. Nothing else needs to change.