How to add zeros to the end of cells
Show older comments
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
Geoff Hayes
on 5 Mar 2018
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?
Lexington Stoyell
on 5 Mar 2018
Geoff Hayes
on 5 Mar 2018
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.
YT
on 5 Mar 2018
seems like a fine way to find the max length if his data is formatted like you assumed (double arrays in cell array).
Jan
on 5 Mar 2018
@Geoff: The built-in methods of cellfun are much faster:
cellfun('size', x, 2)
Geoff Hayes
on 5 Mar 2018
@Jan - I didn't realize you could do that!
Lexington Stoyell
on 5 Mar 2018
Answers (1)
Walter Roberson
on 5 Mar 2018
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
Lexington Stoyell
on 5 Mar 2018
Walter Roberson
on 5 Mar 2018
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.
Lexington Stoyell
on 6 Mar 2018
Walter Roberson
on 6 Mar 2018
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);
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!