Rearranging of matrix in order to avoid loop
5 views (last 30 days)
Show older comments
Thomas G on 24 Jul 2017
Commented: Jan on 25 Jul 2017
In the following code, my goal is to avoid the for-loop (i=1:m). I have already tried several things, but all of them failed.
m = 3;
n = 10;
ii = [1:n;3:n+2;2:n+1]; % index vector with size (m,n)
jj = [3:n+2;2:n+1;1:n]; % index vector with size (m,n)
load E.mat %external file see attachment
res = zeros(n,n,m);
res(:,:,i) = E(ii(i,:),jj(i,:),1,1);
How can I avoid the loop? In the attachment you can find the reference output matrix res.mat which contains the matrix res generated by this code. A code without the loop should reproduce the result saved in res.mat.
Stephen23 on 25 Jul 2017
Edited: Stephen23 on 25 Jul 2017
>> II = repmat(permute(ii,[2,3,1]),1,10,1);
>> JJ = repmat(permute(jj,[3,2,1]),10,1,1);
>> rex = E(sub2ind(size(E),II,JJ));
ans = 1
Jan on 25 Jul 2017
@Thomas G: As a rule of thumb vectorized code is faster than loops, if no huge intermediate index or data arrays are created. When the data process in a loop match into the processor cache, this is a big advantage, and the best vectorized method is lame, if virtual memory must be used, because the physical RAM is exhausted.
Matlab does not parallelize magically. But some commands are multi-threaded, e.g. sum, filter, min, etc. Above a certain size of inputs the work is distributed to the available cores. You can check this roughly in the task manager.
More Answers (1)
Saeed Bello on 25 Jul 2017
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!