for-loop vectorization and structure

조회 수: 1 (최근 30일)
Romain W
Romain W 2012년 3월 8일
Hello all,
I've tried to vectorize the following for-loop:
for i=1:ne
S(1,i).P(1,1).x = [v_proj(fv(i,1),1) v_proj(fv(i,2),1)
v_proj(fv(i,3),1)];
S(1,i).P(1,1).y = [v_proj(fv(i,1),2) v_proj(fv(i,2),2)
v_proj(fv(i,3),2)];
S(1,i).P(1,1).hole = 0;
end
But unfortunately I did not manage to do so. I've tried what follows:
S(1:ne).P.x = [v_proj(fv(1:ne,1),1) v_proj(fv(1:ne,2),1) v_proj(fv(1:ne,3),1)];
Even though everything turns out to be correct for the right-hand side, it does not work for the left one as I would have expected. Can anyone help? Because I really need to feed this structure in a more efficient way and increase original poor speed of the algorithm.
Thank you very much for your help,
Regards,
% Romain

채택된 답변

Walter Roberson
Walter Roberson 2012년 3월 8일
t = mat2cell( [v_proj(fv(1:ne,1),1) v_proj(fv(1:ne,2),1) v_proj(fv(1:ne,3),1)], ones(1,ne), 3);
[S(1:ne).P.x] = t{:};
This is not tested but it looks about right.
  댓글 수: 3
Romain W
Romain W 2012년 3월 8일
@Walter: thank you for your reply, unfortunately I get the same error message as in what I've tried to do so far: "??? Scalar index required for this type of multi-level indexing."
@Jan: if the error mentioned above can be fixed,I will post a timing comparison using my data. And thank you for your reply again.
Jan
Jan 2012년 3월 8일
The [S(index).B.C] operation does not work for non-scalar "index". Matlab resolves on level of substructs only, e.g. [S(index).B].

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2012년 3월 8일
The vectorized version will not be faster, as far as I can see.
Creating the potentially large array [v_proj(fv(1:ne,1),1) v_proj(fv(1:ne,2),1) v_proj(fv(1:ne,3),1)] will allocate a lot of memory. Spliiting it afterwards to vectors will require more memory. Therefore the overall procedure is most likely less efficient than your FOR-loop.
Please try this:
P.hole = 0;
for i = ne:-1:1 % Backwards for implicite pre-allocation
P.x = [v_proj(fv(i,1),1), v_proj(fv(i,2),1), v_proj(fv(i,3),1)];
P.y = [v_proj(fv(i,1),2), v_proj(fv(i,2),2), v_proj(fv(i,3),2)];
S(i, 1).P = P;
end
what is v_proj and fv? Arrays or functions? Would something like this work:
t = fv(i, 1:3);
P.x = v_proj(t, 1);
P.y = v_proj(t, 2);
  댓글 수: 1
Romain W
Romain W 2012년 3월 8일
Thank you for your reply. I am gonna try your solution. v_proj is a matrix size [ne x 2]

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by