I try to let the laptop identify an increase in any vakue of a heatmap grid and if the value increase then that grid will be converted to green but I couldnt let that work.

35 views (last 30 days)
%here's the code I use for testing but whenever I run the code the numbers that didn't increase also convert into green
clearvars;
x = 15;
y = 15;
matrix = randi([0, 3], x, y);
previousMatrix = matrix;
h = heatmap(matrix);
colorbar;
cmap = [linspace(0, 0, 256)' linspace(0, 1, 256)' linspace(1, 0, 256)'];
colormap(cmap);
h.ColorLimits = [0, 5];
for iteration = 1:10
rowToChange = randi(x);
colToChange = randi(y);
roll = randi([1, 6]);
fprintf("Dice Roll: %d\n", roll);
oldValue = matrix(rowToChange, colToChange);
matrix(rowToChange, colToChange) = matrix(rowToChange, colToChange) + roll;
if matrix(rowToChange, colToChange) > oldValue
matrix(rowToChange, colToChange) = 5;
end
% Only re-create the heatmap here after making the updates
h = heatmap(matrix);
colormap(cmap);
h.ColorLimits = [0, 5]; % Ensure only cells with value 5 are highlighted
previousMatrix = matrix;
pause(1);
end

Answers (1)

Shashi Kiran
Shashi Kiran on 7 Nov 2024 at 11:00
I have reviewed your code and have a few observations:
  • In the code segment below, consider a scenario where the old value is 2, and the roll value is 1 (the minimum possible). When you add the roll value to the old value, the result is 3, which will always be greater than the old value.
  • Consequently, the `if` block is always executed, causing the color to change to green regardless.
roll = randi([1, 6]); % 1
oldValue = matrix(rowToChange, colToChange); % 2
matrix(rowToChange, colToChange) = matrix(rowToChange, colToChange) + roll; % 3
if matrix(rowToChange, colToChange) > oldValue
matrix(rowToChange, colToChange) = 5;
end
Please review this logic. Let me know if I can assist you further.

Categories

Find more on Data Distribution Plots in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!