Accumulating different sized column vectors stored as a cell array into a matrix padded with NaNs

前端 未结 2 1222
隐瞒了意图╮
隐瞒了意图╮ 2020-12-21 16:49

Imagine I have a series of different sized column vectors inside an array and want to group them into a matrix by padding the empty spaces with NaN. How can I d

2条回答
  •  执念已碎
    2020-12-21 17:06

    If you want speed the cell data structure is your enemy. For this example I will assume you have this vectors stored in a structure called vector_holder:

    elements = fieldnames(vector_holder);
    
    % Per Dan request
    maximum_size = max(structfun(@max, vector_holder));
    
    % maximum_size is the maximum length of all your separate arrays
    matrix = NaN(length(elements), maximum_size);
    
    for i = 1:length(elements)
        current_length = length(vector.holder(element{i}));
        matrix(i, 1:current_length) = vector.holder(element{i});
    end
    

    Many Matlab functions are slower when dealing with cell variables. In addition, a cell matrix with N double-precision elements requires more memory than a double-precision matrix with N elements.

提交回复
热议问题