How can I make each cell array consistent in length?
15 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Zara Khan
am 7 Mär. 2019
Kommentiert: Zara Khan
am 19 Mär. 2019
In a cell array each element is 1Xlength. This length is not equal. I want to get the maximum length and then want to make each cell with same length by padding zeros in it.
0 Kommentare
Akzeptierte Antwort
Jos (10584)
am 18 Mär. 2019
A final attempt to answer this question :-)
C = {1:4 1:2 ; 1:5 1:6 ; 1 1:3} % a m-by-n cell array
N = cellfun(@numel, C) % old lengths of cell elements
M = 3 ; % new length should be multiple of M
newN = M * ceil(N / M) % new lengths of cell elements
padfun = @(k) [C{k} zeros(1, newN(k) - N(k))] ;
C2 = arrayfun(padfun, 1:numel(C) , 'un', 0) ; % apply padding to all elements of C
C2 = reshape(C2, size(C)) % reshape (if needed)
5 Kommentare
Jos (10584)
am 19 Mär. 2019
After you calculated the new N you can use this:
tf = ~(N < M) % true for the large cells
newN(tf) = N(tf) % reset to the old lengths
Weitere Antworten (3)
tmarske
am 7 Mär. 2019
Bearbeitet: tmarske
am 7 Mär. 2019
%set up a dummy example
tst = {[1 1], [1 1 1 1 1], [1 1 1], [1]}
%get the maximum length
maxlen = max(cellfun(@length, tst))
%pad zeros
tstPadded = cellfun(@(x)([x zeros(1, maxlen - length(x))]), tst, 'UniformOutput', false)
13 Kommentare
Jos (10584)
am 18 Mär. 2019
Your question reads otherwise ... " I want to get the maximum length and then want to make each cell with same length by padding zeros in it.
Jos (10584)
am 7 Mär. 2019
Bearbeitet: Jos (10584)
am 8 Mär. 2019
If you make them the same length, you can also store them in a matrix. In that case, my PADCAT function is your friend :-)
C = {[1 2] ; 1 ; [1 2 3]}
[M, tf] = padcat(C{:}) % pads with NaNs
M(~tf) = 0
PADCAT can be found on the File Exchange, for free:
(edited answer)
6 Kommentare
Jos (10584)
am 8 Mär. 2019
My mistake, should be square brackets of course ... (I edited my answer).
(assuming you also downloaded and installed the function)
Jos (10584)
am 18 Mär. 2019
C = {1:3 4 ; 5:9 10:12 ; 13:14 15} % a m-by-n cell array
N = cellfun(@numel, C)
maxN = max(N(:))
padfun = @(v) [v zeros(1, maxN - numel(v))] ;
C2 = cellfun(padfun, C , 'un', 0)
3 Kommentare
Jos (10584)
am 18 Mär. 2019
I do not get this error in the above code for a cell array like this
C = {[1 0 0 1], [0 1] ; [1 0 1 0], [0 0 1]}
You should give more details about the error and the input ...
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!