Matlab实时绘制3D圆柱图问题求助:自定义colormap失效、实时编辑器不显示
问题排查与修正方案
根因与对应修正点
- 每次弹出新figure窗口:原代码在for循环内部调用了
figure,每次循环都会创建新画布,将figure挪到循环外,且循环内不重复创建surf对象,仅更新其数据属性即可,还可大幅提升更新流畅度。 - 自定义colormap失效:原代码硬编码了
colormap('parula'),直接覆盖了加载的自定义色卡,将该参数替换为mat文件中存储的色卡变量名即可。 - 实时编辑器无法显示:实时编辑器对频繁新建图形对象的支持较差,统一提前定义所有静态绘图属性(轴范围、光照、色轴范围等),循环内仅修改已有surf对象的属性,即可正常在实时编辑器内嵌入显示。
- 隐藏bug修正:原代码中
tsize = size(T)返回的是二维向量,直接作为循环上限会导致循环次数异常,修正为tsize = size(T,1)直接取表格行数;同时原主程序调用的getHeatMap和实际定义的函数名getCylinderHeatMap不一致,已统一。
修正后完整代码
主程序
clc; clear all; close all; filename = ['*The file pathway*' 'filenames.txt']; T = readtable(filename); tsize = size(T,1); % 提前加载自定义色卡 load('newColorMap.mat'); % 提前创建画布、固定所有静态绘图属性 fig = figure(); ax = axes(fig); axis(ax,[0 400 -200 200 -200 200]) colorbar(ax) colormap(ax, newColorMap) % 若mat文件内色卡变量名不同,替换为实际变量名即可 lighting(ax,'gouraud') camlight(ax) material(ax,'dull') caxis(ax,[0 80]) hold(ax,'on') % 预创建surf对象 filename = strcat('*The file pathway*', string(T{1,1})); heat = double(getCylinderHeatMap(filename)); [X,tY] = meshgrid( linspace(1,400,size(heat,2)),linspace(0,2*pi,size(heat,1))); max_heat = max(heat, [], 'all'); min_heat = min(heat, [], 'all'); R = (((heat-min_heat)/(max_heat-min_heat))*50)+100; Y = cos(tY) .* R; Z = sin(tY) .* R; [nx, ny, nz] = surfnorm(X,Y,Z); nv = reshape([nx ny nz], size(nx,1),size(nx,2),3); s = surf(ax,X,Y,Z,heat,'VertexNormals',nv, 'EdgeColor','none'); % 循环更新帧 for i = 2:tsize filename = strcat('*The file pathway*', string(T{i,1})); heat = double(getCylinderHeatMap(filename)); [X,tY] = meshgrid( linspace(1,400,size(heat,2)),linspace(0,2*pi,size(heat,1))); max_heat = max(heat, [], 'all'); min_heat = min(heat, [], 'all'); R = (((heat-min_heat)/(max_heat-min_heat))*50)+100; Y = cos(tY) .* R; Z = sin(tY) .* R; [nx, ny, nz] = surfnorm(X,Y,Z); nv = reshape([nx ny nz], size(nx,1),size(nx,2),3); % 仅更新surf的数据属性,不新建对象 s.XData = X; s.YData = Y; s.ZData = Z; s.CData = heat; s.VertexNormals = nv; drawnow limitrate % 加limitrate避免卡顿,若需要控制速度可加pause(0.1)调整停留时长 end
getCylinderHeatMap函数
function heat = getCylinderHeatMap(filename) s = dir(filename); fin = fopen(filename,'r'); I=fread(fin,s.bytes,'uint8=>uint8'); w = uint16(I(1))+256*uint16(I(2)); h = uint16(I(3))+256*uint16(I(4)); skip = s.bytes - w*h + 1; IN = I(skip:1:s.bytes); Z=single(reshape(IN,w,h)); Z=griddedInterpolant(Z'); y_range = linspace(1.0,single(h),360); x_range = linspace(1.0,single(w),512); heat = uint8(Z({y_range, x_range})); end
额外注意事项
如果加载newColorMap.mat后色卡仍然无法正常显示,可在加载语句后运行who命令查看mat文件导出的变量名,替换代码中colormap调用的参数即可。
内容的提问来源于stack exchange,提问作者Codexing
相关产品推荐
相关产品推荐

