Vectorize a for loop and if-else statement
Mostra commenti meno recenti
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 Commenti
Stephen23
il 10 Mar 2016
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
il 10 Mar 2016
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
il 10 Mar 2016
Stephen23
il 10 Mar 2016
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
il 10 Mar 2016
Ced
il 10 Mar 2016
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
il 11 Mar 2016
Risposte (0)
Categorie
Scopri di più su Matrix Indexing in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!