输入颜色个数n,颜色类型:
n = 2; % 输入颜色个数
colors = {[1, 0, 0], [0, 0, 1]};
createGradientHeatmap(n, colors);
调用函数:
function createGradientHeatmap(n, colors)% 输入检查if length(colors) ~= nerror('输入的颜色数量与n不一致!');end% 创建渐变色gradientColors = zeros(200, 3); % 200行RGB颜色for i = 1:n-1startColor = colors{i};endColor = colors{i+1};% 插值计算当前段颜色range = linspace(0, 1, ceil(200/(n-1)));for j = 1:3gradientColors((i-1)*ceil(200/(n-1)) + (1:length(range)), j) = ...interp1([0 1], [startColor(j) endColor(j)], range);endendgradientColors = gradientColors(1:200, :); % 确保200个渐变% 创建20x10热力图矩阵heatmapMatrix = reshape(1:200, [20, 10]);% 绘制热力图figure('Position', [100, 100, 800, 400]); % 设置画布大小imagesc(heatmapMatrix);colormap(gradientColors);colorbar;title('Gradient Heatmap');axis equal tight;% 添加黑色分割线hold on;[rows, cols] = size(heatmapMatrix);for i = 1:rows+1plot([0.5, cols+0.5], [i-0.5, i-0.5], 'k', 'LineWidth', 1); % 横向分割线endfor j = 1:cols+1plot([j-0.5, j-0.5], [0.5, rows+0.5], 'k', 'LineWidth', 1); % 纵向分割线endhold off;% 保存高清图片saveas(gcf, 'gradient_heatmap_with_lines.png');disp('热力图已保存为gradient_heatmap_with_lines.png');
end%示例调用
%n = 3; % 输入颜色个数
%colors = {[1, 0, 0], [0, 1, 0], [0, 0, 1]}; % 红-绿-蓝渐变
%createGradientHeatmap(n, colors);
结果: