MATLAB: Colour bars in a plot by data values

coloured barsfor loopMATLABplotting

Hello Community,
I am looking to colour some bar plots individually when a condition is met, ie if they have a value of 4, they will be coluored green, if valued 3 they are magenta and so on.
Following an answer I found by Andrew Schultz here I have put the following together:
% run for loop to colour data individually & when data conditions are met
for i = 1:length(pltvar1srt)
h=bar(i,pltvar1srt(i));
if pltvar1srt(i) == x2634(1,11) && x2634(1,16)
set(h,'FaceColor','b');
hlegend(1) = h;
elseif pltvar1srt(:,2) == 4
set(h,'FaceColor','g');
hlegend(2) = h;
elseif pltvar1srt(:,2) == 3
set(h,'FaceColor','m');
hlegend(3) = h;
elseif pltvar1srt(:,2) == 2
set(h,'FaceColor','r');
hlegend(4) = h;
else pltvar1srt(:,2) == 1
set(h,'FaceColor','k');
hlegend(5) = h;
end
end
but unfortunately what happens is I get a single bar coloured 'b' – so the first condition is met, but the rest of the bars end up coloured 'k', so the last condition is met and overwrites all the other colours.
Could anyone advise on how to fix my loop please?
Many thanks,
10B.

Best Answer

In any case, here's one way to do it, assuming your initial condition is as you want it.
for i = 1:length(pltvar1srt)
h=bar(i,pltvar1srt(i));
if pltvar1srt(i) == x2634(1,11) && x2634(1,16)
barColor = 'b';
else
switch pltvar1srt(i)
case 4
barColor = 'g';
case 3
barColor = 'm';
case 2
barColor = 'r';
case 1
barColor = 'k';
otherwise
error('Unhandled case\n');
end
end
set(h, 'FaceColor', barColor);
hlegend(i) = h;
end
Switch is far preferred in cases where it can be used. It is faster and is clearer what is going on. Also note that for switch, you can make several cases have the same outcome by making it a cell. Such as
case {4,5,6}
Would make it so that if the value were 4 5 OR 6, it would do the code in the nest.