How to decrease run time in swap operation ?

1 visualización (últimos 30 días)
cglr
cglr el 23 de Nov. de 2019
Respondida: Guillaume el 23 de Nov. de 2019
Hi everyone,
I make the swap operation as shown below but it consumes time too much. Could you have any offer for swap operation in 2D array ?
while (firstPeriod <= totalPeriod && secondPeriod <= totalPeriod)
temp = myArray(firstPeriod, firstTelegramArray);
myArray(firstPeriod, firstTelegramArray) = myArray(secondPeriod, secondTelegramArray);
myArray(secondPeriod, secondTelegramArray) = temp;
firstPeriod = firstPeriod + rate;
secondPeriod = secondPeriod + rate;
end
Thanks in advance.

Respuestas (2)

Walter Roberson
Walter Roberson el 23 de Nov. de 2019
Editada: Walter Roberson el 23 de Nov. de 2019
Before loop:
mysz = size(myArray);
In loop:
idx1 = sub2ind(mysz, firstPeriod, firstTelegramArray);
idx2 = sub2array(mysz, secondPeriod, secondTelegramArray);
myArray([idx1 idx2]) = myArray([idx2 idx1]);
This can be made more efficient at the expense of being less clear.

Guillaume
Guillaume el 23 de Nov. de 2019
What's the purpose of the while loop since you know beforehand when it ends and thus how many steps it will do?
Assuming that firstTelegramArray and secondTelegramArray are distinct (or that there's no overlap between the periods) your code is equivalent to:
%assuming that firstPeriod is initially StartfirstPeriod (not shown in your code)
%assuming that secondPeriod is initially StartsecondPeriod (not shown in your code)
firstPeriod = StartfirstPeriod:rate:totalPeriod;
secondPeriod = StartsecondPeriod:rate:totalPeriod;
%in case the two vectors have different length crop to the shorter one (same way the while loop behaves
minlength = min(numel(firstPeriod), numel(secondPeriod));
firstPeriod = firstPeriod(1:minlength);
secondPeriod = secondPeriod(1:minlength);
%now do all the swaps, this may be faster than using a temporary variable
indicesfirst = sub2ind(size(myArray), firstPeriod, repelem(firstTelegramArray, minlength));
indicessecond = sub2ind(size(myArray), secondPeriod, repelem(secondTelegramArray, minlength));
myarray([firstindices, secondindices]) = myarray([secondindices, firstindices]);

Categorías

Más información sobre Startup and Shutdown en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by