How to Mark the Intersection Point of Two Plots in MATLAB
The technical computing language MATLAB is used for data processing and analysis in engineering and science-related applications. Data represented in one-dimensional arrays are often compared by plotting the vectors against one another on the same plot. Plotting visualizes the data and shows the points of interest, including the maximums and minimums of the data and intersection points between the two data sets. Frequently, large data sets intersect more than once, making finding all of the intersection points tedious. MATLAB has a built-in function to find all the intersection points between the data sets, which speeds up the analysis process. After finding all the intersection points, labeling the intersection points can also be done.
Clear all active variables in the workspace by entering "clear all" in the MATLAB Command window.
Create example data to plot. First input "x=1:1:10;" into the Command window. Next input "y=rand(1,10);" and "z=rand(1,10);". These commands will create a 10-element array starting at 1 and ending at 10 for "x" and random 10-element arrays for "y" and "z."
Create an intersection point for "y" and "z" from Step 2. Input "y(5)=0.5" and "z(5)=0.5" into the Command window. This will replace the 5th column in "y" and "z" with the number 0.5, which will be the intersection point.
Use MATLAB to find the intersection point between the "y" and "z" vectors. Input "[c, ia, ib]=intersection(y,z)" into the Command window. This will output "c=0.5", which is the intersection value of "ia=5" and "ib=5," the location of the intersection for the "y" and "z" vectors.
Plot the data created in Step 2 and the intersection point found in Step 5. Input "plot(x,y); hold on; plot(x,z); hold on; plot(ia,c,'.')" into the Command window. This will open a new window titled "Figure 1," which shows two line plots for the "y" and "z" data and places a point at (5,0.5), marking the intersection between the two vectors.
Click on the "Data Cursor" icon from the Figure menu. Label the location of the intersection point by left clicking on the dot identifying the intersection. A box will appear with the x and y coordinates. In this example, the box will display "x=5" and "y=0.5."
Tips & Warnings
- If the data contains multiple intersection points, each output of the "intersection" command in Step 4 will contain the value and location of each intersection. For example, if the data intersects three times, "c", "ia" and "ib" will each be a three-element array.