Pass Contents of Cell Arrays to Functions

These examples show several ways to pass data from a cell array to a MATLAB® function that does not recognize cell arrays as inputs.

Pass the contents of a single cell by indexing with curly braces, {}.

This example creates a cell array that contains text and a 20-by-2 array of random numbers.

randCell = {'Random Data', rand(20,2)};
plot(randCell{1,2})
title(randCell{1,1})

Plot only the first column of data by indexing further into the content (multilevel indexing).

figure
plot(randCell{1,2}(:,1))
title('First Column of Data')

Combine numeric data from multiple cells using the cell2mat function.

This example creates a 5-by-2 cell array that stores temperature data for three cities, and plots the temperatures for each city by date.

temperature(1,:) = {'01-Jan-2010', [45, 49, 0]};
temperature(2,:) = {'03-Apr-2010', [54, 68, 21]};
temperature(3,:) = {'20-Jun-2010', [72, 85, 53]};
temperature(4,:) = {'15-Sep-2010', [63, 81, 56]};
temperature(5,:) = {'31-Dec-2010', [38, 54, 18]};

allTemps = cell2mat(temperature(:,2));
dates = datenum(temperature(:,1), 'dd-mmm-yyyy');

plot(dates, allTemps)
datetick('x','mmm')

Pass the contents of multiple cells as a comma-separated list to functions that accept multiple inputs.

This example plots X against Y , and applies line styles from a 2-by-3 cell array C.

X = -pi:pi/10:pi;
Y = tan(sin(X)) - sin(tan(X));

C(:,1) = {'LineWidth'; 2};
C(:,2) = {'MarkerEdgeColor'; 'k'};
C(:,3) = {'MarkerFaceColor'; 'g'};

plot(X, Y, '--rs', C{:})

Related Topics