Plotting a cell array

为君一笑 提交于 2020-01-16 03:59:06

问题


I need to plot a cell array with the following format in Matlab:

{[vector1], [vector2], ...}

Into a 2D graph with the index of the vector as the y and the vector as the x

([vector1], 1), ([vector2], 2), ...

回答1:


Here's a simple option:

% some arbitrary data:
CellData = {rand(10,1)*50,rand(10,1)*50,rand(10,1)*50};

% Define x and y:
x = cell2mat(CellData);
y = ones(size(x,1),1)*(1:size(x,2));

% plot:
plot(x,y,'o')
ylim([0 size(x,2)+1])

so you plot each vector of x on a separate y value:

It will work as long as your cell array is just a list of vectors.

EDIT: For non equal vectors

You'll have to use a for loop with hold:

% some arbitrary data:
CellData = {rand(5,1)*50,rand(6,1)*50,rand(7,1)*50,rand(8,1)*50,rand(9,1)*50};

figure;
hold on
for ii = 1:length(CellData)
    x = CellData{ii};
    y = ones(size(x,1),1)*ii;
    plot(x,y,'o')
end
ylim([0 ii+1])
hold off

Hope this answers your question ;)




回答2:


Here's my (brute force) interpretation of your request. There are likely more elegant solutions.

This code generates a dot plot that puts the values from the vectors at each index on the y axis—bottom to top. It can accommodate vectors of different lengths. You could make it a dot plot of vector distributions, but you might need to add some jitter to the x value, if multiple occurrences of identical or nearly identical values are possible.

% random data--three vectors from range 1:10 of different lengths
for i = 1:3
    dataVals{i} = randi(10,randi(10,1),1);
end

dotSize = 14;
% plot the first vector with dots and increase the dot size
% I happen to like filled circles for this, and this is how I do it.
h = plot(dataVals{1}, ones(length(dataVals{1}), 1),'.r');
set(h,'markers', dotSize);

ax = gca;  
axis([0 11 0 4]);  % set axis limits
% set the Y axis labels to whole numbers
ax.YTickLabel = {'','','1','','2','','3','','',}';

hold on;
% plot the rest of the vectors
for i=2:length(dataVals)
    h = plot(dataVals{i}, ones(length(dataVals{i}),1)*i,'.r');
    set(h, 'markers', dotSize);
end
hold off




回答3:


Without any data this is the best I can come up with for what you want:

yourCell = {[0,0,0],[1,1,1],[2,2,2]}; % 1x3 cell
figure; 
plot(cell2mat(yourCell));
ylabel('Vector Values'); 
xlabel('Index of Vector');

It makes a plot like this:

Hope this helps.



来源:https://stackoverflow.com/questions/38401031/plotting-a-cell-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!