Monday, April 23, 2012

coding with Vectors algebra using the Accelerate framework

I'm playing around with the Accelerate framework for the first time. I've never tried to do anything close to linear algebra in XCode. Having some experience with MATLAB, I wonder if using Accelerate is indeed that much more of a pain. Suppose I'd want to calculate the following:



b = 4*(sin(a/2))^2 where a and b are vectors.



MATLAB code:



a = 1:4;
b = 4*(sin(a/2)).^2;


However, as I see it after some spitting through the documentation, things are quite different using Accelerate.



My C implementation:



float a[4]  = {1,2,3,4};                        //define a
int len = 4;
float div = 2; //define 2
float a2[len]; //define intermediate result 1
vDSP_vsdiv(a, 1, &div, a2, 1, len); //divide
float sinResult[len]; //define intermediate result 2
vvsinf(sinResult, a2, &len); //take sine
float sqResult[len]; //square the result
vDSP_vsq(sinResult, 1, sqResult, 1, len); //take square
float factor = 4; //multiply all this by four
float b[len]; //define answer vector
vDSP_vsmul(sqResult, 1, &factor, b, 1, len); //multiply

//unset all variables I didn't actually need


Honestly, I don't know what's worst here: keeping track of all intermediate steps, trying to memorize how the arguments are passed in vDSP with respect to VecLib (quite different), or that it takes so much time doing something quite trivial.



I really hope I am missing something here and that most steps can be merged or shortened. Any recommendations on coding resources, good coding habits (learned the hard way or from a book), etc. would be very welcome! How do you all deal with multiple lines of vector calculations?





No comments:

Post a Comment