|
Dear all,
I have written a code as below, using two loops. Is there a smart way to use vectorization instead of using loops to speed it? I mean, without loops or only one loop? Since the current code is inside some main program and it does substantially impose the computation burden when I run the whole program each time.
The code is to solve the following problem:
to express a matrix D_{ni} where the subscript {ni} means the nth row, the ith column element in matrix D. D is a N*N matrix. D must satisfy the following condition (the writing follows the format of Latex):
D_{ni}=\sum_{j=1}^{N} y_{nij} * b_{j} * {\min_{m=1,2, ..., N} [c_{m}*K_{nm}*L_{mj}]}
where D, K, L are N*N matrix. b and c are N*1 vector. y is N*N*N (3-dimension). Suppose b, c, K, L are given. We know y_{nij}=0 if i~=m and y_{nij}=1 if i==m. I mean, if i is the index which minimizes the last part (inside the \min symbol), then this y_{nij}=1. If there are more than one index to minimize the last part, we evenly give the weight to each index. Therefore, ultimately, we have \sum_{i} y_{nij}=1
i, j, n, m are all indexes which is taken from 1 to N. Now we need to express this D matrix. We can know that we only need to consider when i (in D_{ni}) equals the index m (i.e., the index which can minimize the last part) and all other D_{ni}=0
My code is as below.
y=zeros(N,N,N);
D=zeros(N);
for n=1:N
for j=1:N
val=c.*K(n,:)'.*L(:,j);
minval=min(val);
minj=find(val==minval);
y(n,minj,j)=1/length(minj);
D(n,minj)=D(n,minj)+minval*b(j)/length(minj);
end
end
If the two loops above can be vectorized, that would be a great help to my program! I hope someone can help me out. Many thanks in advance!
All my best,
Yao (Amber)
|