简体   繁体   中英

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) .

I want to plot grid with the s as blue dots and i as red dots, and the axis take the 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. The second output will provide the index of the label. You can then use imagesc with a custom colormap to display the result.

% 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', []}

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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