代码美学:MATLAB制作渐变色

输入颜色个数n,颜色类型:

Matlab 复制代码
n = 2; % 输入颜色个数
colors = {[1, 0, 0], [0, 0, 1]}; 
createGradientHeatmap(n, colors);

调用函数:

Matlab 复制代码
function createGradientHeatmap(n, colors)
    % 输入检查
    if length(colors) ~= n
        error('输入的颜色数量与n不一致!');
    end
    
    % 创建渐变色
    gradientColors = zeros(200, 3); % 200行RGB颜色
    for i = 1:n-1
        startColor = colors{i};
        endColor = colors{i+1};
        % 插值计算当前段颜色
        range = linspace(0, 1, ceil(200/(n-1)));
        for j = 1:3
            gradientColors((i-1)*ceil(200/(n-1)) + (1:length(range)), j) = ...
                interp1([0 1], [startColor(j) endColor(j)], range);
        end
    end
    gradientColors = 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+1
        plot([0.5, cols+0.5], [i-0.5, i-0.5], 'k', 'LineWidth', 1); % 横向分割线
    end
    for j = 1:cols+1
        plot([j-0.5, j-0.5], [0.5, rows+0.5], 'k', 'LineWidth', 1); % 纵向分割线
    end
    hold 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);

结果:

相关推荐
小徐不徐说2 小时前
序列化与反序列化:把 C++ 对象可靠地保存下来
开发语言·数据库·c++·php
ragnwang3 小时前
Notes: Python pybind11 import C++ module
开发语言·c++·python
Wang's Blog3 小时前
Java 项目实战: 交友项目 - 搜索附近的功能概述和分析
java·开发语言·交友
骑着蜗牛撵大象3273 小时前
大模型 Agent 的沙箱护栏:gVisor 隔离、出口白名单与审计闭环
java·开发语言·jvm·安全·agent沙箱·gvisor·microvm
Dxy12393102164 小时前
JS DES 加密详解
开发语言·javascript·arcgis
充值内卷4 小时前
我给桌面加了个鱼缸:C++ 写后端,WebView2 里养一座 Three.js 小岛
开发语言·javascript·c++
云和数据.ChenGuang4 小时前
深入解析 Python 的 dir():从用法到 CPython 源码实现
开发语言·人工智能·python·langchain
nice_lcj5205 小时前
深入理解 Java 反射:从 Class 对象到方法调用(含性能实测 + 迷你 IOC 实战 + 面试考点)
java·开发语言·后端·面试
樱花树下的数学喵7 小时前
手写简易 STL string|C++ 字符串底层实现
开发语言·c++
jimy17 小时前
C++ 报错的 qualifiers 的意思
开发语言·c++