Main Content

# 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 Contents of 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 cell2mat

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,:) = {'2020-01-01', [45, 49, 0]};
temperature(2,:) = {'2020-04-03', [54, 68, 21]};
temperature(3,:) = {'2020-06-20', [72, 85, 53]};
temperature(4,:) = {'2020-09-15', [63, 81, 56]};
temperature(5,:) = {'2020-12-31', [38, 54, 18]};

allTemps = cell2mat(temperature(:,2));
dates = datetime(temperature(:,1));

plot(dates, allTemps)

### Pass Contents of Multiple Cells as Comma Separated List to Function

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{:})