How do I replace my for loops using matrix manipulation?
2 ビュー (過去 30 日間)
古いコメントを表示
I want a more efficient way to do a window search between two images. I currently have two images; a small clip, and a larger image the clip should be a part of. I want to compare the small clip to every possible subset of the larger image to build a map of mutual information values. I can do this with a for loop as shown below.
dim_Large = size(Large);
dim_Clip = size(Clip);
for j = 1:dim_Large(1)-dim_Clip(1)
for k = 1:dim_Large(2)-dim_Clip(2)
map(j,k) = ...
ent(Large(j:j+dim_Clip(1)-1,k:k+dim_Clip(2)-1),Clip);
end
end
The 'ent' function is code to calculate the mutual information between two matrices of the same size. This does what I need it to do, but is very slow.
I'm sure there is a better way to write this for MatLab, something like
map = ent( Large(1:dim_Large(1)-dim_Clip(1)-1,1:dim_Large(2)-dim_Clip(2)-1), Clip);
but I can't get it to work.
Is there a more efficient way to write this code, preferably one that uses no for loops?
1 件のコメント
Rik
2017 年 11 月 29 日
This depends entirely on the contents of the ent function. Without it, it is impossible to answer this question.
採用された回答
Jan
2017 年 11 月 29 日
The speed of your code depends on two points:
- The speed of the function ent()
- The number of times this function is called
There is no magic way to reduce one or both.
Use the profiler to find the bottleneck of the code. Then start with improving the corresponding code lines.
But I assume, a real speed-up needs a vectorization, e.g.
ent(Large(:, 1:dim_Large(2)-dim_Clip(2)-1), Clip)
Now the complete columns of Large are used and one loop can vanish. If this is possible depends on the contents of ent(), and it is not guaranteed, that it is faster.
3 件のコメント
Jan
2017 年 11 月 30 日
If you only need the first output of ent(), omit the expensive calculation of the 2 others. By the way: x.^-1 is much more expensive than 1./x.
Please use tic/toc to find if this improves the speed:
function jhist = ent2(J, K)
dimen = 256;
x = numel(J);
t = 1:x;
xx = J(:)+1;
yy = dimen*K(:);
xx = sort(xx + yy);
yy(1:x-1) = xx(2:x);
zz = yy - xx;
zz(x) = 1;
zz = t(zz ~=0);
yy = xx(zz);
t = numel(zz);
zz(2:t) = zz(2:t)-zz(1:t-1); % Better: diff(zz)
jhist = zeros(dimen);
jhist(yy) = zz / x;
end
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で MATLAB Compiler についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!