Removing rows and columns from MATLAB matrix quickly

后端 未结 2 1569
难免孤独
难免孤独 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.
    

提交回复
热议问题