简体   繁体   English

如何在Matlab中绘制单元格阵列

[英]How to plot a cell array in Matlab

I am modeling a SIR disease spreading model in Matlab, I have a grid which is a cell array, and each cell mean a state (s,i,r) . 我正在Matlab中建立SIR疾病传播模型,我有一个网格,它是一个单元格阵列,每个单元格表示一个状态(s,i,r)

I want to plot grid with the s as blue dots and i as red dots, and the axis take the length(Grid) . 我想以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'     []     []     []     []

You can use ismember to find where each label exists in your cell array. 您可以使用ismember查找每个标签在单元格数组中的位置。 The second output will provide the index of the label. 第二个输出将提供标签的索引。 You can then use imagesc with a custom colormap to display the result. 然后,可以将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)

And if we test this with Grid = {'s', []; 'i', []} 如果我们使用Grid = {'s', []; 'i', []} Grid = {'s', []; 'i', []}

在此处输入图片说明

If you want actual dots instead, you can do something like this: 如果您想要实际的点,则可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM