I was asked recently (well sort of) to give an example of saving an image to the server. If you look at teethgrinder's example for this, you will see that he has made available an external interface to do just that - POST your graph as png raw data to your server for storage. This has many benefits such as saving the image for use in a PDF report or for printing, since we know at times it is a bit troublesome to print the embedded flash object.
I think the main problem people are having with this is the receiving of the image data post - see the upload_image method below. Also, teethgrinder's example never really says where to make the post_image() call. So I touch on both in the code below.
Here is an example of the png that is saved when I did this for the chart in the previous example:
Well, let's just get right in to the code.
The controller contains the same code as my last post with only a few minor changes to the index method and the addition of the upload_image method.
In the controller, I have this:
12345678910111213141516171819202122
classTestItController < ApplicationControllerdefindex# note the user of open_flash_chart_object_from_hash instead of just open_flash_chart_object# this allows you to pass in the id of the div you want the the chart to be in# this is useful for when we need to findSWF by this id@graph = open_flash_chart_object_from_hash("/test_it/chart", :div_name => "my_chart")end# added to recieve the post data for the OFC png image of the OFC graphdefupload_image name = "tmp_image.png" || params[:name]# the save_image method that is provided by the OFC swf file sends raw post data, so get to it like this data = request.raw_postFile.open("#{RAILS_ROOT}/tmp/#{name}", "wb") { |f| f.write(data) } if data render :nothing => trueenddefchart# same code from here - http://pullmonkey.com/2010/01/05/open-flash-chart-ii-x-axis-date-and-time/ ...endend
So just note the use of open_flash_chart_object_from_hash() in the index method, this way we can pass in the id of the div.
Really the only difference from what we would normally have in our view is that I am using the save image setup method that was added to the open flash chart ruby on rails plugin in the last couple hours (as of this post). The save_image method takes some arguments, mainly the url to post the image data to and the id of the chart we setup in the controller.
Just as an attention grabber - we are going after this example in this article:
Keeping up
Ok, seeing that the php versions of open flash chart and open flash chart swf files continually change along with with the API (not saying this is a bad thing), I wanted to come up with an even more abstract solution. The goal is to not have to worry when the swf file is released with the latest set of graphs or changes its API. I simply don't want to worry about this method or that method, or this class or that class.
Feedback
This article will sort of act as a tutorial for those interested in metaprogramming and as a set of instructions for those looking to experiment with the latest version of the OFC II Rails Plugin that I am currently toying with. I would like to hear feedback, but just remember that phase 1 of this release will be very basic, meaning none of the ajaxy stuff. It will come, just not yet.
Let's see what we can get away with
I am already using method_missing() for pretty much everything in the OFC II Rails Plugin that is being used now. But every time new classes are added, I have to sit down and basically convert the php class to ruby - just plain tedious, not really what I had planned when I started all this. Ok, so method_missing() was great, but let me introduce (or possibly reintroduce) you to const_missing(), basically method_missing() but instead of methods, we can create classes or modules or other objects on the fly. This will definitely help when the php version gets a new class. Instead of getting hounded to update the rails version to be 100% like the php version, everything will just work, no updates to code required. Well, we hope ! So check this out:
Here is what we did with method_missing():
1234567891011121314151617181920212223
moduleOFCclassBasedefmethod_missing(method_name, *args, &blk)case method_name.to_swhen/(.*)=/# i.e., if it is something x_legend=# if the user wants to set an instance variable then let them# the other args (args[0]) are ignored since it is a set methodself.instance_variable_set("@#{$1}", args[0])when/^set_(.*)/# backwards compatible ... the user can still use the same set_y_legend methods if they wantself.instance_variable_set("@#{$1}", args[0])elseif inst = self.instance_variable_get("@#{method_name}") instelse# if the method/attribute is missing and it is not a set method then hmmmm better let the user knowsuperendendendendend
This just basically allows me to do this:
12345678910111213
classFoo < OFC::Baseend foo = Foo.new foo.some_random_attribute = "Hello"#=> "Hello" foo.some_random_attribute #=> "Hello" foo.some_random_undefined_attribute #=> Method Missing error (calls super)# too be like php, for easier conversion foo.set_some_random_attribute("Good Bye") #=> "Good Bye" foo.some_random_attribute #=> "Good Bye"
Along the same lines, I have created an initialize method that takes any argument hash of variable/value pairs and calls variable=() which is handled by method missing as we saw above:
Ok, so on to const_missing() and what we can do with that:
123456
defOFC.const_missing(const) klass = Class.new OFC::BaseObject.const_set const, klassreturn klassend
This says that any undefined (missing) constant of OFC should be defined as a new class that inherits from OFC::Base.
So when we say OFC::Foo, that has not been defined, so we will get back class OFC::Foo < OFC::Base;end; which will give us the initialize() method and method_missing() method from above. Let's see how this works:
So it all sort of came together right there. I've shown you all the code that comes with the Rails Open Flash Chart plugin now. No more definining idividual classes, no more trying to keep up with the never ending php version, and no more late nights converting php to ruby (!). About dang time.
Ok, but this is just the beginning, nothing has been set in stone, so like I said, give me your feedback, what works for you and what does not. And, hopefully, I will have solutions for you or you for me.
Example with new version (test version)
I am using rails 2.3.2, but I don't think it will matter what version you are using.
Create your new rails project
12345
# create a new rails project > pullmonkey$ rails testing_it#<Bunch of stuff is created ....>> pullmonkey$ cd testing_it/
Install the plugin from the test branch
Note the -r test in this next step. The new version (test version) I am playing with is under the test branch and -r says what branch to pull from.
Also, you can use git:// instead of http:// below, but depending on your firewall restrictions http:// will probably work out best for you.
> pullmonkey$ ./script/generate controller test_it# <And more stuff >
Get our assets
1234567
# first we will get swfobject.js> pullmonkey$ cp vendor/plugins/open_flash_chart/assets/javascripts/swfobject.js public/javascripts/# next the open flash chart swf (GET whatever is the latest version), right now that is here: http://teethgrinder.co.uk/open-flash-chart-2/open-flash-chart.swf> pullmonkey$ cd public/> pullmonkey$ wget http://teethgrinder.co.uk/open-flash-chart-2/open-flash-chart.swf> pullmonkey$ cd ..
Edit our controller
Notice here that I just include one of the many examples from the plugin's examples directory. Definitely more to follow.
One thing you will notice about the examples, is that the php code is in the comments, so you can see how I would convert from the php examples to ruby. Please feel free to add your own examples, just fork the project.
12345678910
> pullmonkey$ vi app/controllers/test_it_controller.rb# mine looks like this:classTestItController < ApplicationController include OFC::Examples::AreaHollowdefindex@graph = open_flash_chart_object(600,300, "/test_it/area_hollow")endend
Edit our view
12345
> pullmonkey$ vi app/views/test_it/index.html.erb# mine looks like this:<%= javascript_include_tag 'swfobject'%><%= @graph %>
Start 'er up
12345
> pullmonkey$ ./script/server# browse to the test_it indexhttp://localhost:3000/test_it
Got an email today, I have seen it before and I am sure it has been going around for years. This time, I thought that I would do an exercise and create a plugin that duplicates what I found in this email. See for yourself.
Here is the email I got:
What I gathered was that the only important letters are the first and last letter of each word, those have to be in the right order. So the rest of the letters can be in any random order. That is what I did - I created a plugin and put it out on github. You can install it like this:
This is a step-by-step tutorial for this assignment and an explanation of the basics of how it works for those that are having a difficult time understanding or just are stuck somewhere. To view the assignment click here.
So for this assignment we are only going to be doing input and output. So the only header file we need is the iostream library.
1234
#include<iostream>using namespace std;
Defining the Node Class
For the node class we need 5 private variables: type, value, node1, node2, next, a constructor, 5 member functions, and a friend class.
Because most of the functions only return a single variable it would be a waste to have the functions outside the class so I put them all inside the class.
So here is what your class should look like:
123456789101112131415161718192021222324252627
class node{protected:int type; // type of componentdouble value; // value of the componentint node1; // first node of the componentint node2; // second node of the component node *next; // pointer to the next node in listpublic: node(int a, double b, int c, int d) { type = a; value = b; node1 = c; node2 = d; }int getType() { return type; }double getValue() { return value; }int getNode1() { return node1; }int getNode2() { return node2; } node *getNext() { return next; } friend class circuit;};
Defining the Circuit Class
For the circuit class we need 2 private variables: first and last, a constructor, a copy constructor, 6 member functions, and a friend function.
For these I will put most of the functions on the outside of the class.
So here is what your class should look like:
12345678910111213141516171819202122
class circuit{protected: node *first; // pointer to first node in list node *last; // pointer to last node in list node *getNode(int & , double & , int & , int & );public: circuit(); circuit(const circuit & ); ~circuit();void insert(int , double , int , int );void insertInFront(node * );void insertInBack(node * , node * );void insertInMiddle(node * , node * , node * );bool remove(int , int );bool isEmpty(); friend ostream & operator << (ostream & , circuit );};
Writing the Actual Functions for the Circuit Class
First, we have the private function getNode. This function creates a new member of the node class and returns the address to it.
12345678
node* circuit::getNode(int &t, double &v, int &n1, int &n2){ node *temp = new node(t, v, n1, n2); assert( temp != 0 );return temp;}
Second, we have the a constructor, a copy constructor, and a class destructor:
This is a step-by-step tutorial for this assignment and an explanation of the basics of how it works for those that are having a difficult time understanding or just are stuck somewhere. To view the assignment click here.
So for this assignment we are going to be doing a lot of math calculations so we are going to need the include the both the iostream and the cmath libraries. We will also need the value of pi.
123456789
#include<iostream>#include<cmath>using namespace std;#define PI 3.141592654orconstdouble PI = 3.141592654;
Defining the Complexn Class
For the complexn class we need 2 private variables r and i, 3 constructors, a copy constructor, 4 member functions, 9 overloaded opperators, and 2 friend functions.
Like the previous program we will define everything with in the class and have the actual functions at the bottom.
So here is what your class should look like (keep in mind that this all goes at the top before the main function):
Writing the Actual Functions for the Complexn Class
First we have the 3 constructors and the copy constructor:
12345678910111213141516171819202122232425
// takes no arguments and sets r and i to 0.0complexn::complexn(){ r = i = 0.0;}// takes 1 argument and sets r to the argument and i to 0.0complexn::complexn(double real){ r = real; i = 0.0;}// takes 2 arguments and sets r to the first and i to the secondcomplexn::complexn(double real, double imag){ r = real; i = imag;}// this is a copy constructor that dereferences the complexn variable if it is referencedcomplexn::complexn(const complexn &c){ r = c.r; i = c.i;}
// takes no arguments and returns the distance from the 0 as a doubledouble complexn::complexabs(){return sqrt(pow(r,2.0) + pow(i,2.0));}// takes no arguments and returns the angle of the complex point as a double in radiansdouble complexn::complexangle(){double angle; // angle of coordinate from positive x axis angle = atan(r / i);if(r < 0 and i >= 0)return PI - abs(angle);if(r < 0 and i < 0)return -(PI - abs(angle));return angle;}// takes no arguments and returns the conjugate of the complex number as a complexn classcomplexn complexn::complexconj(){ complexn temp = *this; // complex number used for calculations temp.i *= -1;return temp;}// takes one complexn type argument and returns the distance between the argument and the current instancedouble complexn::distance(const complexn &temp){return sqrt(pow(temp.r -r, 2.0) + pow(temp.i - i, 2.0));}
This is a step-by-step tutorial for this assignment and an explanation of the basics of how it works for those that are having a difficult time understanding or just are stuck somewhere. To view the assignment click here.
So for this assignment we are going to be doing a lot of math calculations so we are going to need the include the both the iostream and the cmath libraries. We will also need the value of pi.
12345678
#include<iostream>#include<cmath>#define PI 3.14159orconstdouble PI = 3.14159;
Defining the Coordinate Class
For the coordinate class we need 2 private variables x and y, 3 constructors, and 11 member functions.
The way you do the constructors and member functions can be done 2 different ways. You can either do them inside the class, or you can define them inside the class, like you do prototypes, and then have the actual functions at the bottom of your code. I like to define them and then put the functions at the bottom, making the code a little bit easier to read so that is the way that I'll show you, but if you want to do it the other way then just do it how you normally would with a regular function.
So here is what your class should look like (keep in mind that this all goes at the top before the main function):
123456789101112131415161718192021222324
class coordinate{private:double x; // x value of the coordinate pointdouble y; // y value of the coordinate pointpublic: coordinate(); // 1st constructor requiring that no arguments are passed coordinate(double ); // 2nd constructor requiring that only 1 argument is passed coordinate(double , double ); // 3rd constructor requiring that 2 arguments are passedvoid set(double , double ); // sets both values and requires 2 arguments to be passedvoid setx(double ); // sets x value and requires 1 argument to be passedvoid sety(double ); // sets y value and requires 1 argument to be passedvoid read(); // allows user to input both x and y values void print(); // prints out the coordinate point in "(x, y)" formdouble distancezero(); // calculates distance of point from zero and returns the valuedouble distancetwo(coordinate ); // calculates distance between 2 points (current instance and coordinate value passed) and returns the valuedouble ranglezero(); // calculates the angle of the coordinate in radians and returns the valuedouble danglezero(); // calculates the angle of the coordinate in degrees and returns the valueint quadrant(); // find what quadrant the coordinate is in and returns the valuevoid midpoint(coordinate ); // calculates the midpoint between 2 points (current instance and coordinate value passed) and prints the value as a coordinate};
Writing the Actual Functions for the Coordinate Class
Since we are not actually writing the functions in the same place we are doing the class we will write them at the bottom after the main function. However, to do this we will need a little more than what we would with regular functions. For member functions we have to define what class the function is actually a member of. To do this we have to do coordinate::[function]().
For example, here are the 3 constructors for the coordinate class:
123456789101112131415161718
// takes no arguments and sets x and y to 0coordinate::coordinate(){ x = y = 0;} // takes 1 argument and sets x and y to that valuecoordinate::coordinate(double a){ x = y = a;} // takes 2 arguments and sets the corresponding x and y to those valuescoordinate::coordinate(double a, double b){ x = a; y = b;}
Next, we have the member functions. The first 3 are the set functions. These allow the user to set the values of either the x or the y or both together.
123456789101112131415161718
// take 2 arguments and sets the corresponding x and y to those valuesvoid coordinate::set(double a, double b){ x = a; y = b;}// takes 1 argument and sets the x to that valuevoid coordinate::setx(double a){ x = a;}// takes 1 argument and sets the y to that valuevoid coordinate::sety(double b){ y = b;}
Next, is the read and print functions. All we want the read to do is to do a cin of the 2 values (x and y). The print is just the opposite. All it does is do a cout of the x and y values in the (x, y) format.
123456789101112
// takes no arguments and reads in the x and y values from the screenvoid coordinate::read(){ cin >> x >> y;}// takes no arguments and prints the x and y values in (x, y) formatvoid coordinate::print(){ cout << "(" << x << ", " << y << ")";}
Next, we have the distance functions. distanczero calculates the distance of the current instance coordinate from 0. distancetwo calculates the distance between 2 points (the current instance and the coordinate passed in).
123456789101112
// takes no arguments and returns the distance of the current instance from zerodouble coordinate::distancezero(){return sqrt(x * x + y * y);}// take 1 argument and calculates the distance between themdouble coordinate::distancetwo(coordinate pt){return sqrt(pow(x - pt.x, 2.0) + pow(y - pt.y, 2.0));}
Next, we have the angle functions. ranglezero uses the function in the math library atan()(arc tangent) to find the angle in radians from the positive x axis. danglezero does the same thing but converts the value from radians to degrees. To convert from radians to degrees you multiply the value by 180 / pi
// takes no arguments and returns the angle of the coordinate from the positive x axis in radiansdouble coordinate::ranglezero(){double angle; // angle of coordinate from positive x axisif(x == 0) // if x == 0 then you will get a domain error so compute angle manually {if(y > 0) return PI / 2;if(y < 0) return -PI / 2;if(y == 0) return0; } angle = atan(y / x);if(x < 0 and y >= 0)return PI - abs(angle);if(x < 0 and y < 0)return -(PI - abs(angle));return angle;}// takes no arguments and returns the angle of the coordinate from the positive x axis in degreesdouble coordinate::danglezero(){double angle; // angle of coordinate from positive x axisif(x == 0) // if x == 0 then you will get a domain error so compute angle manually {if(y > 0) return90;if(y < 0) return -90;if(y == 0) return0; } angle = atan(y / x) * 180 / PI;if(x < 0 and y >= 0)return180 - abs(angle);if(x < 0 and y < 0)return -(180 - abs(angle));return angle;}
Next, we have the quadrant function. This looks at whether the x and y values are positive or negative to determine which quadrant the coordinate is in. It will return the number of the quadrant as an integer 1-4 and 0 if the coordinate is (0, 0)
1234567891011121314
int coordinate::quadrant(){if(x > 0 && y >= 0)return1; // return quadrant 1if(x <= 0 && y > 0)return2; // return quadrant 2if(x < 0 && y <= 0)return3; // return quadrant 3if(x >= 0 && y < 0)return4; // return quadrant 4return0; // return 0 if point is (0, 0)}
Last, we have the midpoint function. you will need to pass this function a coordinate instance and it will calculate the midpoint between the current instance and the passed instance and print the coordinate instance.
This is a step-by-step tutorial for this assignment and an explanation of the basics of how it works for those that are having a difficult time understanding or just are stuck somewhere. To view the assignment click here.
Part A
1. Create a structure (called point) that includes a time and y value (both doubles).
This is very simple using the typedef struct and listing your variables.
1234567
typedefstruct{double time;double y;} point;
2. Create a main program that has an array of 40 points (or structures), keeps track of the number of values in the array and has variables for each of the values needed to calculate above.
In the main program we will need an array of points p, an integer with the total number of points values, and 4 double variables, one for each of the functions (I used vert_shift, amp, freq, and phase_shift).
Then you will need to call each function and for testing I printed each value out to make sure everything was coming in right. It is short, simple, and to the point like all programming should be. Your main should look something like this:
3. The main program should then call the read_data function. This function will have one argument (the array of points - or structures - which will be passed as a pointer to the function) and will return the number of values in the array. It should read the data from the data file using a pointer and the arrow (->) operator.
First, we are going to be reading from a file in this function so we are going to need to include the fstream library.
123
#inlcude <fstream> // reading from file
Next, we need to create the prototype for this function called read_data. This will go above the main. The read_data function will need the array of points and will return the total number of points as an integer. So it should look like this:
123
int read_data(point *);
Now below the main we can create our function and lets call the array of points a. In this function we will need 2 more variables, an integer (total) for counting the number of points that we read from the file and an ifstream variable (f) for opening and closing the file.
First, we need to try to open the file using f.open("sp09prog1.txt"). Next, we need to test to make sure the file was opened and that we can read from it and if not then print out error message and exit. If the file was opened then we need to read in the values into the point array and count the number of points using the total integer variable. We do this until we read the end of the file and we find out if we are at the end of the file with f.eof(). Finally, we will want to return the total. It should look like this:
1234567891011121314151617181920212223
int read_data(point *a){ ifstream f; // file streaming variableint total=0; // counts the total number of points in file f.open("sp09prog1.txt");if(f.fail()) { cout << "ERROR: File could not be opened" << endl; exit(1); }while(!f.eof()) { f >> a->time >> a->y; total++; a++; }return total - 1;}
Notice that we return total - 1. This is because we increment total and then we find out it is the end of the file. So we incremented one too many times so we need to subtract 1 before returning it.
4. Main should then call the vertical function to calculate the vertical shift. This function has two arguments (the array of points - passed as a pointer - and the number of values in the array). It will calculate the vertical shift by finding the average of the maximum and minimum y-values. You will need to search through the array of points to find these max and min values. 5. Next, main will call the amplitude function to calculate the amplitude. This function has two arguments (the array of points - passed as a pointer - and the number of values in the array; you must also use the arrow operator in this function) and will return the amplitude. To find the amplitude, you need to calculate half the difference between the maximum and minimum values of the y-values (you will need to search through the array for the maximum and minimum values again).
The functions are both almost identical. The only difference is the equation at the end so we will do them at the same time.
First, we will create the prototypes. Both functions take the array of points and the integer total number of points and they both return a double. So the prototypes should look like this:
1234
double vertical(point *, int );double amplitude(point *, int );
So lets call the point array p and the integer total.
To find the max and min values we need to create 2 double variables (max and min) and an integer (lcv) that we will use for the loop.
Next we will need to set both max and min to the first y element in the array of points. Then we will have a loop and start from 0 to total. Each time we run through this loop we need to do 3 things:
1. Test if max is less than the current y value? If yes then set max to the current y
2. Test if min is greater than the current y value? If yes then set min to the current y
3. Increment a to the next position in the array. Because we are using a pointer to the array we can do this easily by doing a++
Next we will just return the result of the equation as a double. So your functions should look something like this:
double vertical(point *a, int total){ double min; // minimum y value found in arraydouble max; // maximum y value found in arrayint lcv; // loop control variable max = min = a->y;for(lcv=0; lcv < total; lcv++) {if(max < a->y) max = a->y;if(min > a->y) min = a->y; a++; }return (max + min) / 2.0;}double amplitude(point *a, int total){double min; // minimum y value found in arraydouble max; // maximum y value found in arrayint lcv; // loop control variable max = min = a->y;for(lcv=0; lcv < total; lcv++) {if(max < a->y) max = a->y;if(min > a->y) min = a->y; a++; }return (max - min) / 2.0;}
6. The next function called by main is the frequency function that has two arguments (the array of points - passed as a pointer - and the number of values in the array; again using the arrow operator to access values) and will return the frequency. To calculate the frequency, find the period which is time difference between the maximum and minimum y-values and multiply by 2. Then, divide to calculate the frequency. Please note that you are using the difference between time values, not the y values, to perform the overall computation. 7. Finally, main will call the pshift function that contains two arguments (the array of points - passed as a pointer - and the number of values in the array; again using the arrow operator to access values) and will return the phase shift or horizontal shift. This shift can be found by finding the average of the time values where the maximum and minimum y-values occur; then subtracting it from half the period (see step 6 to find the period).
The functions for steps 6 and 7 are both almost identical expect for the equation at the end so we will do these both at the same time.
For the frequency function we will need to use the absolute value function in the cmath library. To include this you will need to do this at the top of your file.
123
#include<cmath>
Like the functions in step 4 and 5 they need to have the array of points and the integer total number of points and they both return a double. So the prototypes should look like this:
1234
double frequency(point *, int );double pshift(point *, int );
So lets call the point array p and the integer total.
To find the max and min values we need to create 2 pointers to point variables (max and min) and an integer (lcv) that we will use for the loop.
Next we will need to set both max and min pointers to the same address as a points which is the first position in the array of points. Then we will have a loop and start from 0 to total. Each time we run through this loop we need to do 3 things:
1. Test if max->y is less than the current a->y value? If yes then set max to the current a address.
2. Test if min->y is greater than the current a->y value? If yes then set min to the current a address.
3. Increment a to the next position in the array. Because we are using a pointer to the array we can do this easily by doing a++
Next we will just return the result of the equation as a double. So your functions should look something like this:
double frequency(point *a, int total){ point *min; // minimum y value location found in array point *max; // maximum y value location found in arrayint lcv; // loop control variable max = min = a;for(lcv=0; lcv < total; lcv++) {if(max->y < a->y) max = a;if(min->y > a->y) min = a; a++; } return abs(PI / (max->time - min->time));} double pshift(point *a, int total){ point *min; // minimum y value location found in array point *max; // maximum y value location found in arrayint lcv; // loop control variable max = min = a;for(lcv=0; lcv < total; lcv++) {if(max->y < a->y) max = a;if(min->y > a->y) min = a; a++; } a -= total;return (2 * PI / frequency(a, total)) / 2 - (max->time + min->time) / 2.0;}
Notice how in the pshift function after the loop we do a -= total. This is because a is currently pointing the last element in the array and if we want to call frequency and pass the address of the first element in the array of points then we need to set a back to the first element.
Also notice that the frequency function uses a variable called PI. This is the value of pi so at the top above the main you will need to define it as a constant. You can do this one of 2 ways:
12345
#define PI 3.14159or constdouble PI=3.14159;
Either way will work but I prefer to use the #define since it uses less memory and only takes more processing when you compile the program not in running it.
Outcome
Using the text file provided this is what I got when I ran the program:
Using MATLAB, you need to plot the original data using the data file sp09prog1.txt. To do this, load the file into MATLAB, then assign the first column to be the x values and the second column to be the y values. You can then use the plot command to plot these (you should only plot the points - not any connecting lines).
This is easy. Use the load() function to read in data from the file into a matrix.
123
table = load('sp09prog1.txt')
Then we need to get the data into arrays of time and y. To do this use matrixvairable(row,column). Use a colon (:) to get everything in either the row or column. In this case we will want all rows in the first column for time and all rows and second column for y.
1234
time = table(: , 1)y = table(: , 2)
Then plot the data using the plot() function. For this you will need to pass 3 things (x values, y values, and symbol). Our x values is the array time and our y values is array y.
123
plot(time, y, 'o')
Then, using the values you found in the C++ program for each of the four variables, create a cosine curve that can be plotted over the data. You will need to create a matrix of x-values that run from 1 to 2π with an increment of π/100. Then, create a matrix of y values using the cosine equation: where vs is the vertical shift, ps is the phase shift, amp is the amplitude and freq is the frequency. Plot these x and y values using a red line.
This is just the same as the first part only we need to find the x and y values using equations. But first lets set all the values we will need for our calculations which we can get from Part A of the program.
Next we will have to create the array x with all the x values. In this case we are going to go from 0 to 2pi and step by pi/100. To do this we have a colon (:) between each argument like this:
123
x = 0 : PI / 100 : 2 * PI
Now, to create the array y with all the y values we use the equation we were given.
123
y = vs + amp * (cos(freq * x - ps))
Now, all we need to do is plot it on the graph. However, we want to plot the new equation on the same plot as the last one. To do this we need to use the command hold on. We also want the new graph to look different so lets make it a full line 4px wide and the color be dark red. Like this:
1234
hold onplot(x, y, '', 'LineWidth', 4, 'Color', [.6 0 0])
Now run it and see if your two line match up at all.
Building on line graph clicking, thanks to the support of a few other people (mentioned throughout the article) we now have bar graph clicking as well. The only down side (if you want to call it that) is that it is experimental in the sense that the open flash chart swf object had to be updated, and the update is not part of the official OFC release (at least not at the time of this writing). No big deal though, just be aware. It is however part of the OFC rails plugin release.
Big thanks goes to Eric for his work on the action script for the bar clicking open-flash-chart swf file - see this forum entry for more details.
Pull the latest from github and make sure to get Eric's swf file (under the assets directory - open-flash-chart-bar-clicking.swf ) and place it under RAILS_ROOT/public
The call to open_flash_chart_object() has changed to accept an optional parameter for the swf file name. I am leaving the original for use as open-flash-chart.swf (which is the default for the swf_file_name param) and added Eric's as open-flash-chart-bar-clicking.swf. See the example below for usage.
classTestItController < ApplicationControllerdefindex@graph = open_flash_chart_object(600,300,"/test_it/graph_code", true, "/", "open-flash-chart-bar-clicking.swf")enddefgraph_code title = Title.new("Bar on-click Example") bar = BarGlass.new# NOTE ... the next two lines are if you want each bar to have a different response when clicked bar_values = (1..9).to_a.map{|x| bv = BarValue.new(x); bv.on_click = "alert('hello, my value is #{x}')"; bv} bar.set_values(bar_values)# if you want a more generic response across all bars, then the following lines would do:# bar.on_click = "alert('hello there')"# bar.set_values((1..9).to_a) chart = OpenFlashChart.new chart.set_title(title) chart.add_element(bar) render :text => chart.to_sendend