我在Matlab中建模SIR疾病传播模型,我有一个网格,它是一个单元格数组,每个单元格意味着一个状态(s,i,r)。
我想绘制网格,其中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' [] [] [] []
答案 0 :(得分: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', []}
如果你想要实际的点,你可以做这样的事情:
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