|
Dear Priya Narayanan!
> I'm having trouble vectorizing nested loops. Eg. How do I vectorize this simple loop?
> for i =1:10
> for j= 1:10
> for k=1:10
> A(i,j,k)= i *j * k;
> end
> end
> end
You can start with a standard method: insert the innermost FOR loop in the calculation:
A = zeros(10, 10, 10); % Pre-allocate!!!
for i = 1:10
for j = 1:10
A(i, j, 1:10) = i * j * (1:10);
end
end
After the pre-allocation, you can omit the indexing for the last dimension in A:
A(i, j, :) = ... % Is enough and faster
In the next step, moving the vector from the FOR loop into the calculation needs a further method, because (1:10) * (1:10) does not create a 2D matrix. But the following does:
A = zeros(10, 10, 10); % Pre-allocate!!!
for i = 1:10
A(i, :, :) = i * transpose(1:10) * (1:10);
end
As you see, the time-consuming "transpose(1:10) * (1:10)" does not change its value in the loop, so it should be move outside:
A = zeros(10, 10, 10); % Pre-allocate!!!
X = transpose(1:10) * (1:10);
for i = 1:10
A(i, :, :) = i * X;
end
From here on I do not know a trivial standard mechanism for further vectorization, but of course it is possible to avoid the last loop also.
If the array is larger, it is usually more effective to process the first dimension at once, because the processed data match into the small processor cache. So it's worth to try something with "A(:, :, k)" instead of the above method.
Have fun when proceeding from this simple start, Jan
|