Orongo
Orongo

Reputation: 295

plotting from cell array of different lengths

this might come as an eco in this forum but I couldn't find a solution that I could apply to my problem. I have a cell of res_A1 of size (1x500) and in each cell there is a vector (1xlength) where length varies. I would like to plot in the same graph every vector or maybe a handful of them. All lines can be in the same color. I have tried following but the graph make no sense

data=res_A1(1,:,end);
plot(cell2mat(data)');

Also I would like to plot the average of the 500 vectors, preferably this should be in the same graph in another color. Is there a nice way of doing this?

Upvotes: 0

Views: 585

Answers (1)

Suever
Suever

Reputation: 65430

You can use cat to combine the vectors along the first dimension. Then you can pass the transpose of this matrix to plot and each column will be plotted as it's own plot.

plot(cat(1, data{:}).');

If we create some example data, this will yield.

data = arrayfun(@(x)rand(1,10), ones(1, 5), 'uni', 0);
plot(cat(1, data{:}).');

enter image description here

If you want specific ones (i.e. [1 3 5]), you can replace : above with the indices of the ones you want.

plot(cat(1, data{[1 3 5]}).');

enter image description here

If you want to plot the average, simply use mean on the result of the call to cat.

avg = mean(cat(1, data{:}), 1);
plot(avg);

enter image description here

And if you wanted it in the same plot:

alldata = cat(1, data{:});
avg = mean(alldata, 1);

% Plot all of the curves
plot(alldata.');

hold on

% Plot the average curve
plot(avg, 'LineWidth', 3, 'Color', [0.5 0.5 0.5], 'LineStyle', '--')

enter image description here

Update

If your data is all different lengths, You have two options, you could plot everything with a loop.

hax = axes;
hold(hax, 'on');

for k = 1:numel(data)
    plot(data{k}, 'Parent', hax);
end

Or you could still try to combine everything into one matrix, padding with NaN values.

% Find the longest vector length
maxlength = max(cellfun(@(x)numel(x), data));

alldata = nan(maxlength, numel(data));

for k = 1:numel(data)
    alldata(1:numel(data{k}),k) = data{k};
end

Then you can plot this and take the mean using nanmean.

plot(alldata);

avg = nanmean(alldata, 2);

Upvotes: 1

Related Questions