Two identical commands take different times to run?

2 次查看(过去 30 天)
I am running this function inside a bigger script:
K11 and K12 are just the same Matrix at start. I have two questions now:
  1. Why is line 11 taking much more than 9? It is the exact same command
  2. Why removing columns is much easier than removing rows?

采纳的回答

Sean de Wolski
Sean de Wolski 2014-3-5
Good questions!
  1. K11 and K12 are just references to K, they have not been copied in memory. When you change it, the reference needs to be severed and the memory copy needs to happen. That's why 9 and 11 are slower because you're also timing the memory copy.
  2. As for columns v. rows, MATLAB is column major; i.e. arrays are stored columnwise in memory. Thus there are fewer operations required to operate on columns because columns are contiguous in memory whereas rows are separate elements.
  3 个评论
Sean de Wolski
Sean de Wolski 2014-3-6
编辑:Sean de Wolski 2014-3-6
All you need to do is potentially change one element in K11 for the memory copy to happen. Probably the most efficicent form of this would be:
X = rand(7500);
Y = X;
Y(1) = Y(1)+0;
I'm not clear on why you want to do this though? You have to do the memory copy at some point, who cares when it happens? If the memory copy never has to happen then that's the best case scenario.
The best way to do this would be to extract from k only the elements you care about so you never need to copy all of the memory (the stuff you're removing anyway) and you don't need to do any removal of elements which is not the fastest operation. For example:
rdkeep = ~rd; % negate
fdkeep = ~fd;
k11 = k(rdkeep,fdkeep); % extract all at once only memory in the keep indices is copied
To the PS, yes! Remove columns first so there are fewer row computations.
Alessandro
Alessandro 2014-3-6
编辑:Alessandro 2014-3-6
I sorted this out, since fd and rd are complementary, I only needed to call:
which is 10 times faster. Thanks a lot!!

请先登录,再进行评论。

更多回答(1 个)

Marta Salas
Marta Salas 2014-3-5
When you create a 2D array, you need to reference each element to its memory address. As a result, for a 2D array, you need to allocate MxN elements in memory (where M is the number of rows and N of columns). Since memory is a linear object, you need to choose how you organize these elements. You have two options “Row major order” or “Column major order”. Matlab choses the Column major order option.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by