I plan on deleting the first row of a matrix multiple times and was wondering what the best/most efficient way of doing this would be.
I know I can do something like this
M(1,:)=[]
or
M = M(2:end)
but I am not sure which is the best way or if there is another better way.
Hey just tested those 2 methods with tic
and toc
This is the code I used:
A=rand(100,100000);
tic
a=A(2:end,:);
t1=toc
tic
A(1,:)=[];
t2=toc
and this is the result:
t1 =
0.0603
t2 =
0.0744
If you use longer columns it gets even more obvious:
A=rand(10000,100);
t1 =
0.0083
t2 =
0.0124
So saving the columns you want to keep seems to be faster.
Edit
It was commented that tic
and toc
are not "trustworthy" in the millisecond domain so it was recommended to use loops to run the code multiple times. But the result doesn't change .
A=rand(100,100000);
size_A=size(A);
tic
for k=1:1:100
A1=A;
A1=A1(2:end,:);
end
t1=toc
tic
for k=1:1:100
A1=A;
A1(1,:)=[];
end
t2=toc
this results in:
t1 =
7.5237
t2 =
15.2234
Generally it might be faster to keep what you want. Depending on the dimensions of your matrix however results may vary. Consider the following test case where two matrices are generated, A1, and B1, of dimension 100x100000 and 100000x100. The results are obtained from the profile viewer but tic toc measurements confirmed these results.
A1=rand(100,100000);
for ii=1:100
A=A1;
A=A(2:end,:);
end
for ii=1:100
A=A1;
A(1,:)=[];
end
B1=rand(100000,100);
for ii=1:100
B=B1;
B=B(2:end,:);
end
for ii=1:100
B=B1;
B(1,:)=[];
end
The results clearly show that the first case (keeping what you want on a matrix with lots of columns) is very slow actually.
There is no clear this or that is faster though. You should try to time for your situation!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.