矩阵中的颜色编码值

时间:2014-08-15 10:36:26

标签: matlab loops matrix colormap

我有一个500x500的单元格矩阵,每次迭代都会更新。我建模随机过程,新值出现或消失。我想要做的是给值-10一个固定的颜色代码(比如绿色和蓝色)。所有其他值(从1到矩阵中找到的最大值)可以是与包含-10的单元格相同的颜色。可以为大于0的所有值插值颜色。我了解caxis功能但这只允许我排除值-10或从-1开始插值。有没有解决这个问题的方法?它也需要是一个快速的解决方案,因为每次迭代都会打印矩阵......

[溶液]

tic
a = randi([-1,10],100,100);
cint = [-1,0,linspace(1,10,10)];
cmap = [0,0,1;0,1,0;autumn(10)];
[~,c] = histc(a,cint);
d = cmap(reshape(c,10000,1),:);
for k=1:3
    im(:,:,k) = reshape(d(:,k),100,100);
end
image(im)    
toc

2 个答案:

答案 0 :(得分:1)

好吧,因为你特意要求一个细胞。

a = randi([-1,10],10,10); % Generate a 10x10 matrix of random integers
a = num2cell(a);
b = [-1,0,linspace(1,10,5)]; % color interval
cmap = [0,1,0;0,0,1;hot(5)]; % colormap with 7 colors
[~,c] = cellfun(@(x) histc(x,b), a, 'un', false); % Find color index
imdataCells = cellfun(@(x) cmap(x,:), c,'un', false); % Get colors

我还没有测试过创建数据的图像,但据我所知(通过查看数据并将a与间隔进行比较)它应该可以工作。

修改

要以正确的格式获取图像数据,可以使用cellfun

转换图像数据
foo = zeros(size(a,1),size(a,2),3);
for k = 1:3
foo(:,:,k) = cellfun(@(x) x(k),imdataCells);
end

答案 1 :(得分:-1)

例如surf()的第四个参数是值的颜色矩阵,您可以更改它或更改使用的颜色映射。这种方法简洁地定义了一个符合您需求的色彩映射:

% Your Data of -1's, 0's and positive values
cdata = num2cell(peaks(500));
cdata = cell2mat(cdata);
cdata(cdata<0) = -1;
cdata(cdata>0 & cdata <1) = 0;

% the plot
figure()
h = imagesc(cdata);

% the colors
N = 20; % number of colors for interpolation
blue2red = zeros(N,3);
for k = 1:N
    blue2red(k,:) =[k/N, 0, 1-k/N];
end

% adjust the colormap
cmap = zeros(N+2,3);
cmap(1,:) = [0,1,0]; % first is green (for -1)
cmap(2,:) = [0,0,1]; % second is blue (for 0)
cmap(3:end,:) = blue2red; % all the rest is an interpolation from blue to red
colormap(cmap)
colorbar

% Test the picture whilst values are updating
for k = 1:1000;
% Test the picture whilst values are updating
for k = 1:1000;
    old_cdata = get(h, 'CData');        
    cdata = old_cdata + (rand(size(cdata))-0.5)*0.1; % assume values get updated
    cdata(cdata<0) = 0; % assume positive values are at least 0
    cdata(old_cdata == -1) = -1; % assume -1 stays -1
    cdata(old_cdata == 0) = 0; % assume 0 stays 0
    set(h, 'CData', cdata);
    drawnow
end
end