How to decrease run time in swap operation ?

2 次查看(过去 30 天)
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.

回答(2 个)

Walter Roberson
Walter Roberson 2019-11-23
编辑:Walter Roberson 2019-11-23
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 2019-11-23
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]);

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by