A simple question

조회 수: 2 (최근 30일)
Saurabh
Saurabh 2012년 2월 7일
I was trying to speed up my code. In general, I am working with big images but to explain my problem, I will take a simple example. First, I executed the following code:
clc;
saturation_map = [ 12 53 65 23; 32 54 65 122; 75 36 587 122 ];
gray_image = [ 6 34 54 11; 21 45 30 4; 21 2 500 10];
index_list = [ 1 2 3 4 5 7 9 10 11];
max_stretch_ratio = 65535;
num_pixels = length(index_list);
tic;
for i = 1:num_pixels
pixel_ratio = saturation_map( index_list(i) ) /gray_image( index_list(i));
if (pixel_ratio < max_stretch_ratio)
max_stretch_ratio = pixel_ratio;
end
end
toc
As for loops decrease the speed of the code, I replaced the for loop with:
pixel_ratio = saturation_map(index_list) ./ gray_image(index_list);
if isempty(index_list)
pixel_ratio = 65535;
end
max_stretch_ratio = min( pixel_ratio) ;
This runs slower than the first one!! Can anyone rectify the problem?

답변 (2개)

Jan
Jan 2012년 2월 7일
If the saturation_map, gray_image and index_list are large, the creation of the temporary arrays is time-consuming. A total of 3 temporary arrays is needed:
  1. temp1 = saturation_map(index_list)
  2. temp2 = gray_image(index_list)
  3. temp3 = temp1 ./ temp2
Then the FOR loop can be faster.
[EDITED]
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
mwSize n_index, i, k;
double *saturation_map, *gray_image, *index_list, m = 65535.0, t;
saturation_map = mxgetPr(prhs[0]);
gray_image = mxGetPr(prhs[1]);
index_list = mxGetPr(prhs[2]);
n_index = mxGetNumberOfElements(prhs[2]);
for (i = 0; i < n_index; i++) {
k = (mwSize) index_list[i];
t = saturation_map[k] / gray_image[k];
if (t < m) {
m = t;
}
}
plhs[0] = mxCreateDoubleScalar(m);
return;
}
Save this as YourFcn.c, compile it using mex, then call it as:
m = YourFcn(saturation_map, gray_image, index_list);
If you find that it is fast enough, be suree to add checks for the type and number of inputs. Otherwise this function let your Matlab session crash in case of a wrong calling style.
  댓글 수: 3
Jan
Jan 2012년 2월 7일
Most likely a C-Mex function will be faster. Do you have a C-compiler inatalled?
Please define "vey large" quantitatively. In this forum this term is used for 100kB and 4GB images.
Andrei Bobrov
Andrei Bobrov 2012년 2월 7일
+1

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


Andrei Bobrov
Andrei Bobrov 2012년 2월 7일
max_stretch_ratio = min(reshape(saturation_map./gray_image,[],1));
  댓글 수: 6
Saurabh
Saurabh 2012년 2월 7일
I also did that :) It takes more time than the for loop
Saurabh
Saurabh 2012년 2월 7일
Time taken by for loop: 0.000003 sec
Time taken by our approach : 0.000011 sec (which is the same as my second approach in gthe original question)

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

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by