How to add zeros to the end of cells

I am looping through data, which are of various lengths. I want to create a cell that will attach zeros to the end of the cells so there is not a dimension mismatch. How do I go about doing this? How do I do this if the first set of data to loop through is not the largest length?

7 Comments

Lexington - to be clear, do you have a cell array with rows of various lengths and you want to pad each row with zeros so that all rows have the same length? Or is your data (that you are looping over) stored in some other manner?
Geoff - You are correct. My rows are of various lengths and I want to add zeros to the end so all rows are the same lenth
If you want to determine the row with the largest number of elements you could use cellarray as
cellfun(@(y)size(y,2),x)
where x is your cell array. For example, if
x = cell(4,1);
x{1} = ones(1,12);
x{2} = ones(1, 4);
x{3} = ones(1,56);
then
>> cellfun(@(y)size(y,2),x)
ans =
12
4
56
0
You can then use max to know that the third row has 56 elements..which means you can then pad all remaining rows with the appropriate number of zeros.
seems like a fine way to find the max length if his data is formatted like you assumed (double arrays in cell array).
@Geoff: The built-in methods of cellfun are much faster:
cellfun('size', x, 2)
@Jan - I didn't realize you could do that!
How do you then add the zeros on the end?

Sign in to comment.

Answers (1)

FirstNCols = @(M,n) M(:,1:n);
PadToN = @(M,n) FirstNCols([M, zeros(size(M,1),n)]);
width_needed = max( cellfun(@(M) size(M,2), YourArray) );
PaddedArray = cellfun(@(M) PadToN(M, width_needed), YourArray, 'uniform', 0);

4 Comments

What are M and n here? The row and column dimensions?
M -- current matrix extracted from the cell array
n -- width to pad to.
Both of those are dummy parameter names standing in for positional parameters of anonymous functions, so you do not need to provide those values yourself. FirstNCols and PadToN are utility functions that make the code easier to write.
When implementing this I get the error as follows:
Error using @(M,n)M(:,1:n)
Not enough input arguments.
Error in @(M,n)FirstNCols([M,zeros(size(M,1),n)])
Error in @(M)PadToN(M,width_needed)
Error in limits (line 34)
PaddedArray = cellfun(@(M) PadToN(M, width_needed), YourArray, 'uniform', 0);
FirstNCols = @(M,n) M(:,1:n);
PadToN = @(M,n) FirstNCols([M, zeros(size(M,1),n)], n);
width_needed = max( cellfun(@(M) size(M,2), YourArray) );
PaddedArray = cellfun(@(M) PadToN(M, width_needed), YourArray, 'uniform', 0);

Sign in to comment.

Asked:

on 5 Mar 2018

Commented:

on 6 Mar 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!