MATLAB Answers

How to change cell colors in uitable

2 views (last 30 days)
Tomas Durak
Tomas Durak on 24 Nov 2020
Answered: Image Analyst on 24 Nov 2020
Im a beginner in matlab and I need to know how can I color cells which are equal with my input table (on the left) in my result uitable (on the right).
My code looks like this:
%Make visual values which coresponds in both vectors
for i=1:number
if matrix1(i,1) == matrix3(i,1)
set(handles.uitable3, 'BackgroundColor', [0 1 0]); %Color green
set(handles.uitable3, 'BackgroundColor', [1 1 1]); %Color white
Matrix1 is input matrix and matrix3 is calculated matrix based on algorithm. I only need to color cells in matrix3 uitable which are equal with matrix1.
Thank you very much.


dpb on 24 Nov 2020
See previous Q <Answers/25038> for options...if you're using R2019b or later, looks like there's now a new feature <AddStyle> available. I've never used so that's all I know...enjoy!
Tomas Durak
Tomas Durak on 24 Nov 2020
Thanks for response.
Yeah I see it but its not working like I want. Maybe its my fault and Im doing something wrong but this not helps me.
But very thanks for comment.

Sign in to comment.

Answers (2)

dpb on 24 Nov 2020
You didn't follow the instructions given at the linked-to Answer. The 'BackgroundColor' property applies to the whole table; you have to use addStyle and a style object to modify individual cells.
See the following simple demonstration -- very similar to the example in the documentation but slightly more representative of your specific object.
M1=randn(4,1);M2=randn(4,1);M2(3)=M1(3); % make up some data and force one match
hUIT1=uitable(hUF,'Data',M1,'Position',[20 20 120 120]);
hUIT2=uitable(hUF,'Data',M2,'Position',[160 20 120 120]);
sHiLite=uistyle; % build the higlight style object
sHiLite.BackgroundColor='green'; % set the color for the highlighted cells
% preliminary work done, the engine...
ix=find(M1==M2); % locate rows that match
addStyle(hUIT1,sHiLite,'cell',[ix,1]) % and set the highlighted rows
You'll need to build the auxiliary style object to turn the highlight color back to whatever you want for default if conditions change and relocate the matches.
Also, if this is floating point comparisons, you'll probably run into issues using "==" in finding exact matches. Look at ismembertol for "close enough" matching.
Follow the general pattern outlined above for your specific need; NB: addStyle works only in UIFigures.
If you're not using UIFIGURE, you'll have to resort to one of the kludges in the other thread...


Sign in to comment.

Community Treasure Hunt

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

Start Hunting!