Azzera filtri
Azzera filtri

How to decrease run time in swap operation ?

2 visualizzazioni (ultimi 30 giorni)
cglr
cglr il 23 Nov 2019
Risposto: Guillaume il 23 Nov 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.

Risposte (2)

Walter Roberson
Walter Roberson il 23 Nov 2019
Modificato: Walter Roberson il 23 Nov 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 il 23 Nov 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]);

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by