How to make cell array same length after padding zeros

孤街醉人 提交于 2019-12-08 07:39:28

问题


This is data matrix having 2*159 cells In the data matrix so many columns ( 2 vectors) having different length . I want to pad zeros which have the minimum length. Number of zeros should be

[max(length(Vector 1))-min(length(Vector 2))]

Now I want add zeros in the cell which have minimum length. and want to make length equal in each column if column have same length than no problem.


回答1:


n = max(max(cellfun(@(x)size(x,2),data)))
cellfun(@(x)[x, zeros(1,n-numel(x))], data, 'uni', 0)

The above was finding one single max value to pad the cells to. I realise now that you actually want this max calculated on a per column basis:

n = max(cellfun(@(x)size(x,2),data))
cellfun(@(x,n)[x, zeros(1,n-numel(x))], data, repmat(num2cell(n),2,1), 'uni', 0)

At this point it might be more intuitive to just use a loop

for col = 1:size(data,2)
    n = max(size(data{1,col},2),size(data{2,col},2));
    for row = 1:2
         x = data{row,col};
         data{row,col} = [x, zeros(1,n-numel(x))];
    end
end


来源:https://stackoverflow.com/questions/37206846/how-to-make-cell-array-same-length-after-padding-zeros

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!