Rearranging of matrix in order to avoid loop

2 次查看(过去 30 天)
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);
for i=1:m;
res(:,:,i) = E(ii(i,:),jj(i,:),1,1);
end
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.
  7 个评论
Stephen23
Stephen23 2017-7-24
编辑:Stephen23 2017-7-24
@Thomas G: I assumed that you are not using random numbers in your calculations, which is why I did not put that as an answer.
However, your question, as posed, is best answered by a simple rand call. Given that you use random numbers to fill that matrix it is impossible to write and test code and know if the matrix has been filled correctly: one random matrix is just as good as another for solving the question that you have asked. Put another way, your question is impossible to falsify: there is no way that we could write code that is wrong, as long as it generates some random numbers. We need to be able to check if code output is wrong.
What would be actually useful is to provide small input and output examples: matrices that actually show what you want to achieve, and that can be used to test code on. You can upload data files by clicking the paperclip button.
Thomas G
Thomas G 2017-7-25
Ok thank you for your hint. I modified the question and added an input and an output file for my loop example. Hope that makes it now precise.

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2017-7-25
编辑:Stephen23 2017-7-25
>> 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));
>> isequal(rex,res)
ans = 1
  5 个评论
Jan
Jan 2017-7-25
@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.

请先登录,再进行评论。

更多回答(1 个)

Saeed Bello
Saeed Bello 2017-7-25
You can try to look up Matrix indexing and Vectorization in MATLAB. Hope this help.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by