Newbiew need help optimizing code and understanding Octave

Ben Abbott bpabbott at mac.com
Tue Apr 1 08:02:31 CDT 2008


On Apr 1, 2008, at 7:13 AM, malhotrag wrote:
>
> Just a correction the loop should be
>
> for widthstrip = 36:2:84
>
> malhotrag wrote:
>>
>> Hi All,
>>
>> Below is the code I am writing as a part of a bigger project. My  
>> Issues
>> are I am an octave newbie and I used to do programming in C/C++ so  
>> I write
>> octave code pretty similar to C/C++ code.
>>
>> The code below runs really slow (it's not that complex though), so  
>> I would
>> like tips from all on how to make it fast. I know I need to  
>> vectorize this
>> but I don't really understand the concept of vectorization and so  
>> need
>> expert advice.
>>
>> Any help would be really appreciated..
>>
>> Thanks
>>
>> h = 80;
>> r = 3.5;
>> s = 12;
>> xmin = 0;
>> xmax = 120;
>> widthstrip = 36;
>> for widthstrip = 82:2:82
>> ymin  = (h/2) - (widthstrip/2);
>> ymax =  (h/2) + (widthstrip/2);
>> Fd12 = 0;
>> sum = 0;
>> count = 0;
>>
>> for i = xmin:xmax
>> 	for j = ymin:ymax
>> 		x = i;
>> 		y = j;
>> 		S = s / r;
>> 		X = x / r;
>> 		Y = y / r;
>> 		H = h / r;
>>
>> 		A = X^2 + Y^2 + S^2;
>> 		B = S^2 + X^2;
>> 		C = (H - Y)^2;
>>
>> 		part1 = S / B;
>> 		part2 = S / (2 * B * pi);
>> 		part3 = acos( (Y^2 - B + 1) / (A - 1) );
>> 		part4 = acos( (C - B + 1) / (C + B - 1) );
>> 		part5 = (A + 1) / (sqrt( (A - 1)^2 + 4 * Y^2 ));
>> 		part6 = acos( (Y^2 - B + 1) / (sqrt(B) * (A - 1)) );
>> 		part7 = (C + B + 1) / (sqrt( (C + B - 1)^2 + 4 * C ));
>> 		part8 = acos( (C - B + 1) / (sqrt(B) * (C + B - 1)) );
>> 		part9 = H * acos( (1/sqrt(B)) );
>>
>> 		sum = sum + (part1 - (part2 * (part3 + part4 - (Y * part5 *  
>> part6) -
>> (sqrt(C) * part7 * part8) + part9)));
>> 		++count;
>> 	endfor
>> endfor
>>
>> Fd12 = sum;
>>
>> printf("\nWidth of %d inch Fd1-2 = %f, Count is %d and Fd1-2 final  
>> = %f
>> ", widthstrip, Fd12,count,Fd12/count);
>>
>> endfor
>>
>

The most effective speed improvement strategy would be to vectorize  
your algorithm.

The idea is to replace

I'm guessing you'd begin by creating a single matrix for x and y.

x = xmin:xmax;
y = ymin:ymax;
X = (ones (numel(x), 1) * x) / r;
Y = (ones (numel(y), 1) * y) / r;
S = S / r;
A = X.^2 + Y.^2 + S.^2;
... etc ...

Ben


More information about the Help-octave mailing list