How do I vectorise a for loop that reorders 4 bytes of an array with each iteration
1 view (last 30 days)
Show older comments
A = uint8(Data); %Assume the data comes in multiples of 4 bytes
B = [];
for byteNo = 1 :4: length(A)-3 % changed 4 to 3 to fix the typo that was flagged by Walter Roberson
B = cat(2,B,[A(byteNo+2),A(byteNo+3),A(byteNo),A(byteNo+1)]);
end
1 Comment
Walter Roberson
on 7 Sep 2016
I suspect the termination should be length(A)-3 rather than -4 . Consider that if A was length 8, then there would be room for two swaps of length 4, but your upper bound would be byteNo = 4 which is before the second lower byteNo needed for the swap, which has to start at byteNo = 5.
Accepted Answer
Walter Roberson
on 7 Sep 2016
If the vector is not a multiple of length 4, discard mod(length,4) values from the end of it. Take the resulting vector and reshape() it into 4 rows. Reorder the rows. Reshape the result into a vector.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!