Vectorize a for loop and if-else statement
이전 댓글 표시
Hello. Can anybody help me to vectorize:
L=1;
A=0;
for L=1:100
for i=1:25
A=A+1;
if E(L).a == N(i).a
HD(A,L)=myfunction(T0,M0,T(i).a,M(i).a);
else
HD(A,L)=0;
end
A=A+1;
if E(L).a == N(i).b
HD(A,L)=myfunction(T0,M0,T(i).b,M(i).b);
else
HD(A,L)=0;
end
end
end
where E,N,T,M are struct. T0 and M0 are 128x720 double. Thanks
댓글 수: 8
Stephen23
2016년 3월 10일
Vectorization does not mean replacing my slow loops with some other code, it means writing functions that operate on entire arrays at once.
This means it is the function that is important, not the loops. However you do not tell us anything about myfunction, yet it is the only important thing to consider. If you give us details about the function then we can give advice about vectorization.
shahrizan jamaludin
2016년 3월 10일
What Stephen meant was how your function computes its output, in this case the hamming distance. If your function does this in vectorized form, it will be more efficient to give it a full vector instead of looping. But this is not always possible.
Example:
% 1: Scalar case
function y = norm_scalar(x)
y = sqrt(x*x);
end
% 2: vector case, but looped
function y = norm_notvectorized(x)
N = length(x);
y = 0;
for i = 1:N
y = y + x(i)*x(i);
end
y = sqrt(y);
end
% 3: vector case, vectorized
function y = norm_vectorized(x)
y = sqrt(x'*x);
end
The scalar case doesn't make much sense here, but couldn't think of anything meaningful right now, and it's just to show the difference:
In case of function 1, you actually cannot pass it a vector. In function 2, you can pass it a vector, but it will perform the operation very inefficiently. function 3 is vectorized, and will be much more efficient than function 2.
In short: The important part is myfunction, not the for loop.
shahrizan jamaludin
2016년 3월 10일
Stephen23
2016년 3월 10일
The answer depends on what happens inside myfunction. You need to understand: vectorization means that myfunction needs to be written using vectorized code. It is not the loop or the allocation that is important: it is the code inside myfunction that we need to check.
When you show us myfunction then we can tell you if it is, or can be vectorized.
shahrizan jamaludin
2016년 3월 10일
Ced
2016년 3월 10일
Have you seen this?
It's not exactly what you asked, but why write something yourself if it already exists? Unless it's a personal exercise, that's always a good reason.
shahrizan jamaludin
2016년 3월 11일
답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!