2016-11-15 32 views
0

我在Matlab中對SIR疾病擴展模型進行建模,我有一個網格,它是一個單元陣列,每個單元意味着一個狀態(狀態爲(s,i,r))。如何在Matlab中繪製單元陣列

我想用s作爲藍色圓點和i作爲紅色圓點繪製網格,軸線爲length(Grid)

Grid = 

    []  [] 's' 's'  []  []  [] 'i'  []  [] 
    's'  [] 's' 's'  []  []  []  [] 's'  [] 
    []  []  []  []  []  []  []  [] 's'  [] 
    []  []  [] 's'  []  []  []  []  []  [] 
    [] 's'  [] 'i' 's'  [] 's' 'i'  [] 's' 
    []  [] 's' 's'  [] 's'  [] 'i' 's' 'i' 
    'i'  []  []  [] 's'  []  []  []  []  [] 
    []  []  [] 's'  []  []  []  []  []  [] 
    [] 's'  []  []  []  [] 'i' 'i' 'i'  [] 
    []  [] 's'  [] 's' 's'  []  []  []  [] 

回答

2

您可以使用ismember來查找您的單元格陣列中每個標籤的存在位置。第二個輸出將提供標籤的索引。然後,您可以使用imagesc和自定義顏色映射來顯示結果。

% Create a copy of Grid where the empty cells are replaced with '' 
tmp = Grid; 
tmp = cellfun(@(x)['' x], Grid, 'UniformOutput', false); 

% Locate all of the 's' and 'i' cells and assign values of 1 and 2 respectively 
[~, labels] = ismember(tmp, {'s', 'i'}); 

% Display the resulting label matrix 
imagesc(labels) 

% Use a custom colormap where empty cells are black, 's' are blue and 'i' are red 
cmap = [0 0 0; 0 0 1; 1 0 0]; 
colormap(cmap) 

如果我們用Grid = {'s', []; 'i', []}

enter image description here

如果你想實際的點,而不是測試,你可以做這樣的事情:

colors = {'r', 'b'}; 
labels = {'s', 'i'}; 

for k = 1:numel(labels) 
    % Find the row/column indices of the matches 
    [r, c] = find(cellfun(@(x)isequal(x, labels{k}), Grid)); 

    % Plot these at points using the specified color   
    plot(c, r, '.', 'Color', colors{k}, 'MarkerSize', 20); 
    hold on 
end