Removing rows and columns from MATLAB matrix quickly

后端 未结 2 1570
难免孤独
难免孤独 2020-12-20 11:36

Is there a fast way to remove rows and columns from a large matrix in MATLAB?

I have a very large (square) distance matrix, that I want to remove a number of rows/co

相关标签:
2条回答
  • 2020-12-20 12:10

    It seems like a memory bottleneck. On my feeble laptop, breaking D up and applying these operators to each part was much faster (using s=12,000 crashed my computer). Here I break it into two pieces, but you can probably find a more optimal partition.

    s = 8000;
    D = rand(s);
    
    D1 = D(1:s/2,:);
    D2 = D((s/2 + 1):end,:);
    
    cols = sort(randsample(s,2));
    rows = sort(randsample(s,2));
    
    A1 = D1;
    A2 = D2;
    
    tic
    A1(rows(rows <= s/2),:) = [];
    A2(rows(rows > s/2) - s/2,:) = [];
    A1(:,cols) = [];
    A2(:,cols) = [];
    toc
    
    A = D;
    tic
    A(rows,:) = [];
    A(:,cols) = [];
    toc
    
    Elapsed time is 2.317080 seconds.
    Elapsed time is 140.771632 seconds.
    
    0 讨论(0)
  • 2020-12-20 12:25

    I think it will depend on your usage, but I have two ideas:

    1. Make it a sparse matrix. The more you're removing the better this option will probably be.
    2. Why do you need to remove the values? Could you maybe do:

    
    A = D(randsample(s,2), randsample(s,2));
    clear D;
    % Use A
    

    0 讨论(0)
提交回复
热议问题