Two identical commands take different times to run?

1 visualizzazione (ultimi 30 giorni)
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?

Risposta accettata

Sean de Wolski
Sean de Wolski il 5 Mar 2014
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 Commenti
Sean de Wolski
Sean de Wolski il 6 Mar 2014
Modificato: Sean de Wolski il 6 Mar 2014
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 il 6 Mar 2014
Modificato: Alessandro il 6 Mar 2014
I sorted this out, since fd and rd are complementary, I only needed to call:
which is 10 times faster. Thanks a lot!!

Accedi per commentare.

Più risposte (1)

Marta Salas
Marta Salas il 5 Mar 2014
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.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by