Octave for Chapter 1
The templates in this section provide sample Octave code for vector operations. You can access our code through the link at the bottom of each template. Feel free to modify the code and experiment to learn more!
You can write your own code using Octave software or online Octave cells. To access Octave cells online, go to the Sage Math Cell Webpage, select OCTAVE as the language, enter your code, and press EVALUATE.
To ”save” or share your online code, click on the Share button, select Permalink, then copy the address directly from the browser window. You can store this link to access your work later or share this link with others. You will need to get a new Permalink every time you modify the code.
Octave Tutorial
Basic Operations
% Define vectors v and w
v=[3;1;1;2;4];
w=[-2;1;0;3;-1];
% Find v+w
sum=v+w
% Find 5v
five_v=5*v
% Find the dot product of v and w
dot_v_w=dot(v,w)
% Find the length of v
length_v=norm(v)
- In Octave, we use to add comments to our code. Octave does not execute anything that appears after on the same line. It is always a good idea to make notes about your code for yourself and others.
- Note that lines 2 and 3 of our code have a semi-column at the end while lines 6, 9, 12, and 15 do not. Remove the semi-column from lines 2 and 3, add semi-columns to the other lines. Run the code. What happens?
% Define vectors v and w
v=[3;1;1];
w=[-2;1;0];
% Find the cross product v x w
cross_v_w=cross(v,w)
Sometimes it is useful to reference a single component of a vector.
Loops
In this section we will introduce one of the most fundamental concepts in programming, a loop. Loops are used to repeat a procedure multiple times. We will start with a simple for loop. Every time you perform the steps inside the loop, you come back to the beginning, and increase the index by 1 until you reach the desired number of iterations.
% Enter the starting value
n=10;
% At every iteration, n gets replaced with n+1
for i=1:10
n=n+1
end
% Enter the first component of vector v
v(1)=1;
% Enter the second component of vector v
v(2)=1;
% we continue to assign values to vector components
for i=1:10
v(i+2)=v(i)+v(i+1);
end
v
Do you recognize this famous sequence?
Octave Exercises
% Enter coordinates of point A
A=[1; 4; 6];
% Enter coordinates of point B
B=[-2; 3; 7]
% Enter coordinates of point C
C=[1; -2; 4]
% Normal vector to the plane containing A, B, C is given by
What type of user inputs (other than all zeros) would result in the computed normal vector of ? Explain this phenomenon geometrically.
Use your code to find an equation of a plane containing points , , .
% Define vectors v and w
v=[3; 6; -1; 7; 12];
w=[-2; 4; -3; 5; 11];
% Initialize the dot product (dp)
dp=0;
% Find the dot product v*w directly from the definition
for i=1:5
dp=dp+;
end
% Print your answer
dp
% Check your answer
correct_answer=dot(v,w)
Why did we have to initialize dp? What would happen if we didn’t?