splitting a matlab matrix into several equal parts

后端 未结 4 1391
死守一世寂寞
死守一世寂寞 2021-01-12 09:22

I have a matrix of size 64500x17. It represents detected texton features that I have to use to find 5 centroids for kmeans.

What I need is:

相关标签:
4条回答
  • 2021-01-12 09:38

    You can use mat2cell and this oneliner

    C = mat2cell(A, repmat(12900, 5, 1), 17);
    

    The second parameter to mat2cell is the row split of the matrix.

    Now C is a cell array:

    C = 
    
    [12900x17 double]
    [12900x17 double]
    [12900x17 double]
    [12900x17 double]
    [12900x17 double]
    

    and the partial matrices can be accessed as

    C{1} etc.
    
    0 讨论(0)
  • 2021-01-12 09:41

    The probably fastest solution is:

    data = rand(64500,17);
    Nsubsets = 5;
    Nsubsize = size(data,1)/Nsubsets;
    joined_means=squeeze(mean(reshape(data,Nsubsize,Nsubsets,size(data,2)),1));
    

    Split the first and second dimension, then you can calculate the mean over the first dimension of Nsubsets elements each.

    0 讨论(0)
  • 2021-01-12 09:46

    To take the first submatrix use colon notation:

    A(1:12900,:)
    

    then

    A(12901:12900*2,:)
    

    and so on.

    0 讨论(0)
  • 2021-01-12 09:48

    Just use indexing and store the extracted matrices in cells for easier handling:

    data = rand(64500,17);
    Nsubsets = 5;
    Nsubsize = size(data,1)/Nsubsets;
    
    splitted_data = cell(Nsubsets ,1);
    splitted_data_means = cell(Nsubsets,1);
    
    for ii=1:Nsubsets 
        splitted_data{ii} = data((ii-1)*Nsubsize + (1:Nsubsize),:);
        splitted_data_means{ii} = mean(splitted_data{ii});
    end
    

    you can then join these means with:

    joined_means = cell2mat(splitted_data_means);
    

    Or just for the heck-of-it with the one-liner:

    joined_means = cell2mat(arrayfun(@(ii) mean(data((ii-1)*12900+(1:12900),:)),(1:5)','uni',false));
    

    which would be even simpler with @angainor's mat2cell:

    joined_means = cell2mat(cellfun(@mean,mat2cell(data, 12900*ones(5,1), 17),'uni',false));
    
    0 讨论(0)
提交回复
热议问题