MATLAB: Two identical commands take different times to run

advanced programmingmemoryspeed

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?

Best Answer

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.