How does MATLAB implement the : operator?
Afficher commentaires plus anciens
Hey folks, i've been learning how indexing works in matlab, and i've come upon a particular problem that i think would benefit from MATLAB's implementation.
So, let's imagine you have a source array that looks like this:
[1 4 7]
[2 5 8]
[3 6 9]
Because of how linear indexing works, i set these values specifically to match the linear index. So if you were to do something like array(:), you'd get [1 2 3 4 5 6 7 8 9].
Now, let's say you you want to access the first and third value from all columns, you'd do something like:
value = array([1, 3], :);
The : operator automatically adds the appropriate bias to the index on every column (so the index matches the linear index), and it does so very efficiently. If you were to mimic this in code, you'd do something like:
array = [1 4 7; 2 5 8; 3 6 9];
[numCols, numRows] = size(array);
index = repmat([1; 3], 1, numCols); % Repeats the index a number of times equal to the amount of columns
for i=1:numCols
index(:, i) = index(:, i) + (i-1) * numRows; % Adds the column index to each column so the linear index matches
end
% Result 1 and 2 are the same
result1 = array(index);
result2 = array([1,3], :);
My problem is, building the index manually takes a lot longer to complete than using the : operator, even if you're comparing the use where the index is already built. Please note, i am comparing the speed of a prebuilt index, so basically just the time it takes to run the line in result1 versus result2.
In my tests, i used huge arrays, because that's where i'll be using this. My guess is that the large array for the index ends up slowing down the code, even if you change the data type to uint16 for example. The only way to avoid this large index array would be to do this in a loop, something like this:
result = zeros(2, 3);
for i=1:numCols
result(:, i) = array((i-1) * numRows + [1 3]);
end
But this slows down the code significantly too. So how does Matlab implement the : operator?
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Matrix Indexing dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!