I have a cell array with nested cell arrays:
I want to plot each nested cell array by rows. But not all nested cell arrays are 8x1. I need to fill in the empy values as NaN or zeros, but still be able to plot the data continously.
example for columns 7-9:
Column7 Column8 Column9
1 1 1
2 2 2
3 NaN NaN
4 NaN NaN
5 NaN NaN
6 NaN NaN
I want to plot by rows, row 1 is (1,1,1), row 2 is (2,2,2), row 3 is (3, NaN, NaN), and so on; So category 7 will have values 1-6 vertically. Category 8 will have values 1 to NaN vertically but only plotting values 1 and 2.
I want row 1 values to connect via line:
Example:
figure
hold on
cellfun(@(C1) plot(cell2mat(C1,:), 'o-'), C);
% setup axes
xlim([0, 15]);
ax = gca;
ax.XTick = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
ax.XTickLabel = {'1','2','3','4','5','6','7','8','9','10','11','12','13','14','15'};
The easiest way to do this, is to build a 2D matrix that contains your data (where present), and NaNs elsewhere. Most plotting commands in Matlab ignore NaNs.
To convert your cell array to a matrix, you can create a matrix containing only NaNs, and fill in the data present column-by-column. For example;
% Create dummy data
C = {[1;2;3;4], [7;7;8], [5;4]};
% Find the maximum number of rows possible across all cells
Nrows = max(cellfun(@length, C));
% Create matrix full of NaNs
M = nan(Nrows, length(C));
% Loop cells
for i = 1 : length(C)
% Pull the contents of this cell
Content = C{i};
% Fill this column with as many rows as we found
M(1 : length(Content), i) = Content;
end
The resulting matrix M
contains the values of each cell in C
, one per column. You can then simply plot them with
plot(M)