簡體   English   中英

矩陣中的顏色編碼值

[英]Color coding values in matrix

我有一個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

好吧,因為您專門詢問了一個牢房。

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

例如surf()的第4個參數是值顏色的矩陣,您可以更改此值或更改使用的顏色圖。 這種簡單的方法可以根據您的需要定義一個顏色圖:

% 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM