Matlab: removes rows / columns from a matrix expensive?

Adding rows / columns to a matrix in MATLAB seems to be pretty much considered. For example, when I tried to add a column to a matrix Athat has many rows and many columns, for example

A = [A, added_col]

Matlab will warn me that since this should make a copy of A in memory, I better use pre-allocation for speed. This is understandable because the underlying data Aoccupies a contiguous block of memory.

My question is, will rows / columns remove similar issues? For example, to delete the second line A:

A(2,:) = []

Is this operation in place or not? I really feel insecure because, on the one hand, it does not create a new room for the data in memory, and for the other, the lines Awill be stored non-contiguously (since line 2 is deleted).

So what will happen inside? And is this operation effective enough for practical use? Thank!


Just tested it with complexity 100000:

clc; clear;
N = 100000;
A = zeros(N, 3);

t1 = tic;
for ii = 1:N
    A(ii, :) = [1 2 3];
end
t2 = toc;

AND

clc; clear;
N = 100000;
A = zeros(N, 3);

t1 = tic;
for ii = (N-1):-1:2
    A(ii, :) = [];
end
t2 = toc;

Results: 0.009s for the first (changing a pre-distributed matrix) and 53.429s for the second (removing rows from the matrix). I think this basically solves this issue: NO, deleting rows / columns from a matrix is ​​NOT efficient to use , as it is definitely related to deep copy of data and memory reallocation.

, . , , - , :

N = 100000;
test_m = zeros(3, N);
tic
for ii = (N - 1):-1:2
    test_m(:, ii) = [];
end
toc
% result: 105.436595 seconds. 
% This was run on a different machine than the previous examples.
% But is still enough evidence that dynamically resizing a big matrix is a BAD idea.

, : , . preallocation.

+4

Source: https://habr.com/ru/post/1689433/


All Articles