How to decrease run time in swap operation ?
1 回表示 (過去 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.
0 件のコメント
回答 (2 件)
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.
0 件のコメント
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]);
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!