None Programming_Resource

What is a Computer Program?

In this course you will write short computer programs to help you solve problems, simulate the behavior of a dynamic system, or plot the results of your calculations. This means it is important for you to understand what a computer program is, and how you might go about writing one.

A computer program is a set of instructions that the computer will execute sequentially (one after the other) to perform a task or set of tasks. In the Jupyter Notebook environment, we write our computer programs in "code cells" and we execute (run) the program by either pressing the "run" button in the menu bar or hitting Shift and Enter at the same time while the cell is in focus (highlighted because you clicked on it or your cursor is inside of it).

Code in Jupyter notebooks can be written in many different languages. In ES103, we will write in the MATLAB language's Open-Source counterpart, Octave. Octave and MATLAB have several very minor differences, but they are almost identical. By learning the Octave language, you will also be learning to program in the MATLAB language. A standalone copy of MATLAB's desktop environment is available to every Lafayette student free of charge. Simply log in to www.mathworks.com using your Lafayette credentials.

An example of a program you could write in Jupyter using the MATLAB/Octave language is shown below. This program calculates the volume of a cylinder based on its radius and height. Run this program to see the results.

In [1]:
% user inputs a radius. try changing this value!
r = .5;
% user inputs a height
H = 2;

% now using the radius and height, calculate volume of the cylinder.
V = pi*r^2*H
V =  1.5708

Note that this program contained lines that are comments marked by the % sign. Comments are not actual instructions to the computer. They are merely to make your program easier for other people to read and understand. Each line of code you write in this course should be preceded by a comment that explains what you intend the next line to do.

Note as well that it used variables defined by the user in the first two lines. Using variables means that you can change your program's inputs easily without changing numeric values in multiple places in your code.

Finally, note that the final line of the program did not end with a semicolon. In the MATLAB/Octave programming language, omitting a semicolon tells the computer to display the results of that line to the user.

Common Elements of a Computer Program

While there are many "custom" or unique parts of any computer program, there are a few things that are nearly always required. Every line in every program you will write for ES103 will fall into one of the following categories.

Variables

Variables in a computer program are "keywords" you use to hold data (often but not limited to scalar, single numbers, groups of numbers in the form of arrays/vectors/matrices, or Boolean True/False values).

Assignment

The act of Assigning data to a variable is one of the most important parts of writing a computer program. In almost all languages, inluding MATLAB/Octave, which we will use in this course, this is done by writing the variable name on the left side of an equals sign, and the data you wish to assign on the right side of the equals sign, as shown in the snippet below. hit Shift+Enter while the cell is selected to run it. Try assigning different values to "a."

In [2]:
a = 2
a =  2

this simple line of code defines the variable "a" as being equivalent to the number "2" so that you can use the variable "a" in subsequent calculations without having to type "2" in each line. This means that you could assign the value of "a" at the top of your code, and if you change that assignment and re-run the code, every calculation that includes "a" will now use the new value.

Note that you cannot, however, reverse the order of "a" and "2" in this program. You can switch the order in the cell above to see that it produces an error.

Input and output

Many programs require interaction with a user. Sometimes, a program will "ask" the user to input certain information. Many languages have specialized functionality to prompt a user for information. Consider the following program, which asks a user to input a number. The program stores this number as a variable using assignment. Uncomment the line and run the cell to see how it works-- it is commented because it waits for user input before continuing!

In [3]:
% my_input = input("pick any number")

We will NOT commonly use the "input" functionality in MATLAB/Octave-- another way to achieve user interaction is to simply change your code so that any variables that are critical to your program's operation are defined at the top of the code. That way, you can simply change a line of code as a way of providing an "input" to the program. In this case, we could have simply had a line of code at the top that said

my_input = 3;

and changed "3" to whatever number we wanted as appropriate.

It is also important that a program is able to show "outputs" to the user, which represent things that the program has produced based on input from the user. In MATLAB/Octave, outputs are often either numerical values or plots. You can find out more about plotting later on in this notebook, but let's imagine that we wanted to write a program that raised any number to any power. We could write the program as follows:

In [4]:
% specify inputs of a and b in the equation a^b
num_to_raise = 2; % "a" in our equation
power_to_raise = 13; % "b" in our equation

%produce the result, which is a^b
result = num_to_raise^power_to_raise
result =  8192

note that by omitting the semicolon in the last line, I have told MATLAB/Octave to display the result to the user!

Retrieval

Once data have been assigned to a variable, you can retrieve the data from that variable to display it to the console or to assign parts of the data to another variable. Let's imagine that you assigned an array of numbers to a variable. you could then retrieve one or more numbers out of that array. See the example below.

In [5]:
% assign data to a variable
my_var = [10 20 30]; %an array of 3 numbers

% retrieve the 2nd number in the array and display it
my_var(2)
ans =  20

Selection

Sometimes, a program will need to do one thing under certain conditions, and another thing entirely if other conditions are met. This is called "selection." One basic mechanism of selection in the MATLAB/Octave language is the "if" statement, which is explained here.

Repetition

Often, the tasks that a program will need to perform have to be repeated. There are structures called "loops" in nearly all programming languages that allow small blocks of code to be run repeatedly. In ES103, the primary structure we'll use for repetition is the for-loop, but while loops are also used.

Other Operations

Other than assignment, Input/Output, Selection, and Repetition, computer programs also perform operations on variables in the program. These could include multiplication, division, raising to a power, or many other types of manipulation. All lines of code are technically "operations," but if those operations do not fall into one of the above categories, we will put them in this "bin."

Planning a Computer Program

You can think of the very simple programs you will write in this course as a numbered list of steps. The computer will do exactly what you tell it to; no more, and no less.

The most important thing that you need to decide before you write any piece of code is what the code's inputs and outputs should be. If the code is a computer model of a dynamic system, its outputs will often be something like plots of the system's behavior as a function of time. Its inputs will often be physical properties of the system (think mass, capacitance, spring constant, etc) and perhaps information about how long the simulation should run for.

After you are confident that you know what should go into and come out of your program, you will need to break up the task or tasks that relate input and output into discrete steps. You can use a flow chart to help you break down the tasks your program should perform into steps that can be turned into a line or a few lines of code. This will help you plan your program and avoid a situation where you're not sure what line of code you should be writing next!

Most issues students have with programming are unrelated to issues with syntax (how to actually write the code) and are instead issues students have with planning. You must know what you want the program to do in each step before writing your code.

You can find some examples of flow charts that describe computer programs at this link. These should help you get started with thinking about how a program can be represented visually as a series of steps. A basic tutorial on how to use www.diagrams.net to create flow charts is here. you can use the snipping tool to turn in a picture of your program's flow chart as part of your assignments in this course!

Basic Operations in the MATLAB/Octave Programming Language

Octave, which is the open-source version of MATLAB, can be used as a simple calculator. Operations are performed one line at at time. See the "cell" below, which defines two variables, adds their values on one line, and then multiplies them on the next. More information about basic arithmetic operations can be found at this link. To "run" or execute the code in this cell, select it, and then hit Shift+Enter (Hold Shift, then hold Enter as well).

Assigning Variables

Variables can have user-defined names like "a" or "orange." They are commonly used to hold numerical information in the form of single numbers or in arrays/matrices for use in later operations. variables must be defined before they can be used in a calculation. Code is read "top to bottom" within a cell, but once a variable is defined in Jupyter, it is not "cleared" unless the kernel is restarted or the "clear all" command is run (usually at the top of a cell).

In [6]:
% a comment, which is not executed, is noted by a %. In Jupyter, make sure this % is followed by a space.
% use comments to tell the reader what we are doing. First, we "define" a variable a to be the number 2.
a = 2; % the semicolon at the end of the line means "don't show me this when you execute the code."
% now, we will define a second variable. Variable names should be descriptive when possible.
b = 3.02;
% now we will add them together. 
c = a+b % note there is no semicolon, which means the code will "Show" us the result
d = a*b %same here. When you run this cell, think about what you expect to see!
c =  5.0200
d =  6.0400

Assigning and accessing data in arrays (Matrices)

Often we need "arrays" or lists of numbers in order to plot data. MATLAB can also perform arithmetic on these, as shown below.

More detailed information about accessing and manipulating arrays in MATLAB can be found here and here.

If you have trouble understanding what is happening in the cell below, I suggest you visit both of these links.

In [7]:
% let's create a matrix (an array) of numbers. One column will represent time, and the other will represent "f," which we have computed as some function of time.
% arrays are defined by row. a semicolon inside the definition of the array, which begins and ends with [], means "create a new row"
data = [ 1  10; 2 11; 3 10; 4 9; 5 8] %no semicolon at the end... we should see this one when we execute.

% let's subtract 1 second from all of the times in 'data.' We can access the "times" in our data, or the first column only, as follows:
data(:,1) = data(:,1)-1 %notice that we have UPDATED all values in the first column of the array. the colon : in data(:,1) represents "all rows" in the "first column"

% Now, let's say we need to convert the units of column 2 from meters to centimeters. We could do this by multiplying all elements in the second column by 100.
data(:,2) = data(:,2)*100

%when you run this cell, you will see "Data" printed three times, with the updates we made as we made them.
data =

    1   10
    2   11
    3   10
    4    9
    5    8

data =

    0   10
    1   11
    2   10
    3    9
    4    8

data =

      0   1000
      1   1100
      2   1000
      3    900
      4    800

Transposing Matrices

Sometimes, it is necessary to transpose a matrix. This can be done using the apostrophe. See the example below:

In [8]:
%define a matrix named a. It has 1 row, 3 columns
a = [1 2 3]
%define a matrix b as the transpose of a. It will have 3 rows, one column.
b = a'
a =

   1   2   3

b =

   1
   2
   3

Matrix and element-wise operations

By default, MATLAB/Octave perform matrix operations between two variables. An example is matrix multiplication, where the code:

a*b

will default to performing matrix multiplication between the two variables. Often, however, we want to multiply every element in a by the corresponding element in b. For this, we need to use the .* operator. Putting a period before an operation like *,^, or / spefifies that you want to do element-wise, rather than matrix, operations between two variables. See the example below.

In [9]:
a = [4 5; 6 7]
b = [10 11; 12 13]

%the following performs matrix multiplication
a*b

%the following performs element-wise multiplication
a.*b

%now let's look at two vectors, t and c.
c = [1 2 3 4]
t = [0 0.1 0.2 0.3]

%to multiply each element in c by each element in t, we need to use element-wise multiplication.
c.*t

%if we try to use matrix multiplication, Octave will throw an error.
c*t
a =

   4   5
   6   7

b =

   10   11
   12   13

ans =

   100   109
   144   157

ans =

   40   55
   72   91

c =

   1   2   3   4

t =

   0.00000   0.10000   0.20000   0.30000

ans =

   0.00000   0.20000   0.60000   1.20000

error: operator *: nonconformant arguments (op1 is 1x4, op2 is 1x4)

The error Octave throws at the end indicates that we're trying to perform an operation between two variables of incompatible size. Recall that for matrix multiplication, the inner dimensions must agree.

Making arrays that increment by a constant value

Often, when creating arrays for things like time, it is useful to create arrays that "count up" by a certain amount. The colon : operator is the way this is done in MATLAB. See the example below.

In [10]:
%create a matrix a that starts at 0, counts up by 0.1, and has a maximum value of 1.
a = 0:0.1:1
a =

 Columns 1 through 7:

    0.00000    0.10000    0.20000    0.30000    0.40000    0.50000    0.60000

 Columns 8 through 11:

    0.70000    0.80000    0.90000    1.00000

Indexing

When a matrix is defined in MATLAB/Octave, you can set or access parts of that matrix by indexing it. See the example below.

In [11]:
%given this matrix a
a = [10 11; 12 13; 14 15]
%I can pull out the value in the 2nd row, 1st column by doing:
my_value = a(2,1)
%Note that MATLAB/Octave allows you to index the LAST row and/or column using the "end" keyword.
last_value = a(end,end)
last_row_first_column = a(end,1)

%I can also SET a value in the matrix the same way. Note that the value in the 2nd row, 1st column changes from 12 to 100
a(2,1) = 100
a =

   10   11
   12   13
   14   15

my_value =  12
last_value =  15
last_row_first_column =  14
a =

    10    11
   100    13
    14    15

Indexing using the colon operator

An entire row or column of a matrix can be set or retrieved using the colon. See the example below:

In [12]:
%given this matrix a
a = [10 11; 12 13; 14 15]
%I can pull out the entire second row by doing:
my_row = a(2,:)
%Or, I could pull out the entire second column by doing:
my_column = a(:,2)
%or, I could set the entire third row in a to something new, like so:
a(3,:) = [1 2]
a =

   10   11
   12   13
   14   15

my_row =

   12   13

my_column =

   11
   13
   15

a =

   10   11
   12   13
    1    2

Loading Files

If a text file is in the same directory as your notebook, it can be loaded as a variable in Octave/MATLAB by using the load() command. See the example below, where we load the text file 'data.txt,' containing the following text:

1, 2
3, 4

Commas, tabs, and whitespace can all be used to separate numbers in a data file.

In [13]:
data = load('data.txt')
error: load: unable to find file data.txt

Clearing the workspace

While cells are run top to bottom, there's nothing stopping you from changing their contents, defining new variables, and overwriting old ones. Variables you define stay in memory until they are "cleared" or overwritten. You can clear all variables and "start fresh" by putting the following at the top of a cell:

clear all

to see what variables are currently defined, you can use the "who" function. Note that in the example below, "who" returns variables before "clear all" is run, but not after, since they have been cleared.

In [14]:
who
my_vars = who
clear all
who
my_vars = who
Variables in the current scope:

H                      data                   my_var
V                      jj                     num_to_raise
a                      last_row_first_column  packs
ans                    last_value             power_to_raise
b                      my_column              r
c                      my_row                 result
d                      my_value               t

my_vars = 
{
  [1,1] = H
  [2,1] = V
  [3,1] = a
  [4,1] = ans
  [5,1] = b
  [6,1] = c
  [7,1] = d
  [8,1] = data
  [9,1] = jj
  [10,1] = last_row_first_column
  [11,1] = last_value
  [12,1] = my_column
  [13,1] = my_row
  [14,1] = my_value
  [15,1] = my_var
  [16,1] = num_to_raise
  [17,1] = packs
  [18,1] = power_to_raise
  [19,1] = r
  [20,1] = result
  [21,1] = t
}
my_vars = {}(0x0)

If-Statements

In MATLAB/Octave, an "if" statement can be used to direct your program to do one thing if certain conditions are met, and another if those conditions are not met. For example, let's say you wrote a code to determine if a number x was divisible by 3. Perhaps this code should return "x/3" if the number is divisible by 3, and show the user a message if it is not. For this example, we will also employ the "modulo" operator mod(), which returns the remainder of one number divided by another. For example, the code mod(5,3) would return "2" since 5/3 has a remainder of "2."

The format for an "if" statement is

if( condition 1 )
    operations to perform if condition 1 is true
elseif (condition 2)
    operations to perform if condition 2 is true
else
    operations to perform if none of the "if" or "else if" conditions are true 
end
In [15]:
x = 3;

if(mod(x,3) == 0) %note the use of the == rather than =. The = operator in MATLAB is for ASSIGNMENT, while == checks equivalence.
    result = x/3
else
    disp('number is not divisible by 3!!')
end
result =  1

For-Loops

In MATLAB/Octave, a "for loop" can be used to perform repetitive calculations easily. The syntax looks like this:

for k=1:10
    (operations to be repeated 10 times go here)
end

the index k begins at 1. Then, whatever operations you need to perform go between the "for" and the "end" lines. Once the loop hits the "end" line, it goes back to the top of the "for" loop and increases k by 1. It does this until k=10. Then, the loop completes for the last time. Let's look at an example, in which we use a for-loop to create an array where each entry is equal to 2*k.

The output a(k) in the code below is unsuppressed, so you can see how the code "builds" the array a one column at a time. If you suppress that line using a semicolon, you will not have to see all of the "intermediate" actions of the code.

In [16]:
% initialize the array
a = zeros(1,5)% this creates an array of all zeros, with dimensions 1 row by 1 columns.

for k = 1:length(a) % notice length(a) here. This automatically sees how many times the loop should run (5 in this case)
    %print k so we can see what it is
    k
    %fill in this entry in a
    a(k) = 2*k
end
a =

   0   0   0   0   0

k =  1
a =

   2   0   0   0   0

k =  2
a =

   2   4   0   0   0

k =  3
a =

   2   4   6   0   0

k =  4
a =

   2   4   6   8   0

k =  5
a =

    2    4    6    8   10

Common MATLAB/Octave Functions

help

The "help" function can be used to find information about any MATLAB/Octave function. See the example below.

In [17]:
help magic
'magic' is a function from the file /usr/share/octave/4.2.2/m/special-matrix/magic.m

 -- magic (N)

     Create an N-by-N magic square.

     A magic square is an arrangement of the integers '1:n^2' such that
     the row sums, column sums, and diagonal sums are all equal to the
     same value.

     Note: N must be a scalar greater than or equal to 3.  If you supply
     N less than 3, magic returns either a nonmagic square, or else the
     degenerate magic squares 1 and [].

Additional help for built-in functions and operators is
available in the online version of the manual.  Use the command
'doc <topic>' to search the manual index.

Help and information about Octave is also available on the WWW
at http://www.octave.org and via the help@octave.org
mailing list.

ones() and zeros()

Often, it is useful to create arrays of a particular size that are filled with a particular number. The ones() and zeros() functions are easy ways to do this. zeros() produces a matrix filled with all zeros, and ones() produces a matrix filled with all ones (this can be used to fill a matrix with any constant number).

See the example below. Both take two arguments. The first one is the number of rows you want, and the second is the number of columns.

In [18]:
%create a 1x10 matrix of all zeros.
a = zeros(1,10)
%create a 2x5 matrix of all ones
b = ones(2,5)
%create a 1x5 matrix of all 3.5
c = 3.5*ones(1,5)
a =

   0   0   0   0   0   0   0   0   0   0

b =

   1   1   1   1   1
   1   1   1   1   1

c =

    3.5000    3.5000    3.5000    3.5000    3.5000

Size

The size() function returns the number of rows and the number of columns in a matrix, in that order. See the example below.

In [19]:
array1 = 0:0.2:10; % here are 3 different arrays each with their own size of values
array2 = 0:0.4:10; 
array3 = [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20];

% to easily find the size of these arrays you can use size(name of array)
% the answer you obtain tells you what your array is like and it comes in 
% the format of rows then columns`

size(array1) 
display('1 row, 51 columns')

size(array2) 
display('1 row, 26 columns')

size(array3) 
display('1 row, 20 columns')

% this function is helpful when trying to assess vector length errors
ans =

    1   51

1 row, 51 columns
ans =

    1   26

1 row, 26 columns
ans =

    1   20

1 row, 20 columns

Length

The length() function returns the largest dimension (rows or columns) in a vector. See the example below.

In [20]:
a = [1 2; 3 4; 5 6]
length(a)
a =

   1   2
   3   4
   5   6

ans =  3

In this case, since "a" had 3 rows and 2 columns, it returns "3" as the length.

plot()

by: Liam T

The plot() function allows us to create figures of our data that we find in an xy plane.

You want to use the format:

figure
plot(x-axis array,y-axis array,'type of line')
xlabel('name of x axis data (w/units)') 
ylabel('name of y axis data (w/units)')
legend('name of the line')

There are many line styles you can use (see "help plot" for more).

They all follow the format: color,point type, line type.

Some examples are given below:

'bo-' gives you a blue(b) line(-) with circle points(o)

'mx--' gives you a magenta(m) dotted line(--) with x points(x)

'k.-' gives you a black(k) line(-) with . points(.)

See the code cell below for some examples

In [21]:
t = 0:2:50; % array for time, starting at 0, counting by 2s up to 50
m = 1/4; % slope of the line
b = 1; % y-intercept
y = (m * t) + b; % equation created for graphing example

figure
plot(t,y,'bo-') % things that are plotted against one another must be the same size
xlabel('time') % name of the first component in plot
ylabel('position (y)') % name of the second component in plot
legend('example') % name of the line that is being graphed

% its also possible to graph more than one line on a certain graph

m2 = 1/2; % new slope
y2 = (m2 * t) + b; % new equation with new slope

% you can create a whole new graph by creating another 'figure'

figure
plot(t,y,'bo-',t,y2,'mx--') % if you wanted to add a third line you would follow this pattern
xlabel('time (s)')
ylabel('position (m)')
legend('example 1','example 2') % because there are 2 lines being graphed you now need 2 names

xlim() and ylim() to set plot limits

You can set the limits of a plot using xlim() and ylim() functions. An example is below.

In [22]:
figure
plot(t,y,'bo-',t,y2,'mx--') % if you wanted to add a third line you would follow this pattern
xlabel('time (s)')
ylabel('position (m)')
legend('example 1','example 2') % because there are 2 lines being graphed you now need 2 names

%now cut off the time so I only look at the first 20 seconds
xlim([0 20])
%now crop in the y so I only look at y values from 2 to 10
ylim([2 10])

find()

The find() function allows to to locate an element in an array that satisfies a condition. Use "help find" to see all of the possible inputs to this function and how to use them. As a quick example, suppose you have the function:

$$y = 1-e^{-t}$$

and you'd like to know at what time this function is first greater than or equal to 0.632. This could be accomplished using the following code:

In [23]:
clear all
%set up variable to hold time values
t = 0:.01:5;
%implement my equation:
y = 1 - exp(-t);
%use find to locate which VALUE in my array y is greater than .632.
my_index = find(y>0.632,1,'first') %tells the find() command to find one index in the array y
%(the first one) for which y is greater than 0.632.
%this index will be an integer between 1 and the length of y, allowing me to use it to "index" the variable
%and find the values I'm interested in

%now, to use this, I would like to see which y value that is, and at what time it occurs:
my_y = y(my_index)
my_time = t(my_index)

%just to make this visual, let's plot y vs. t, and also plot our "found" value on top.
figure
plot(t,y,'k',my_time,my_y,'ro','MarkerSize',15)
xlabel('Time (s)')
ylabel('Y (quarks)')
legend('y','first point where y greater than 0.632')
my_index =  101
my_y =  0.63212
my_time =  1

polyfit()

MATLAB/Octave can be used to estimate a "best fit" polynomial function to match a dataset. The term "best fit," in this context, means that the sum of the squared error between the model and the data is minimized. The command used to produce the set of coefficients is "polyfit." An example of how to use the "polyfit" command to produce the best-fit line for a dataset is shown below.

In [24]:
% first, create some fake "data" we will fit a line to, in order to see how "polyfit" works.
xfakedata = 0:.1:10;
yfakedata = -3*xfakedata + 4 + .5*randn(size(xfakedata)); %the randn() on the end produces some random "noise" on our fake data.
%this simulates the effect of having error in our measurements. If polyfit does its job, we should get the line y = -3x+4 back!

%now we will actually use polyfit. The array "coefficients" will contain [m b] in the equation y = m*x+b.
%the second argument to the polyfit() function is the ORDER of the polynomial. A line is a polynomial of order 1. 
%for reference, a quadratic is a polynomial of order 2.
coefficients = polyfit(xfakedata,yfakedata,1); 
%was m=-3 and b=4?
m_estimate = coefficients(1)
b_estimate = coefficients(2)

%now, these coefficients fully define a "model" of our relationship y = m*x+b. Let's produce predictions based on this model
ymodel = m_estimate*xfakedata + b_estimate;

%now plot the data and the model together to evaluate.
figure
plot(xfakedata,yfakedata,'ks',xfakedata,ymodel,'r')
xlabel('x')
ylabel('y')
legend('data','model')
m_estimate = -2.9870
b_estimate =  4.0360

Common Errors

Errors are common, even if you're an expert programmer. Reading the error carefully will give you an idea of what is wrong with your code. Below are some common error archetypes and some hints about what they mean. As you debug your code, talking your way through every term in every line can help!

error: index (something): out of bound 1

This usually means you're trying to index a variable that is either not a matrix, or is a matrix that is too small for the index you're requesting. See the example below:

In [25]:
% set a as one number
a = 1;
%try to access the 3rd element in a
a(3)
%let's say b is actually a matrix
b = ones(2,2)
%but we try to access the 3rd row, 1st column. The error looks slightly different, but the effect is the same.
b(3,1)
error: a(3): out of bound 1
b =

   1   1
   1   1

error: b(3,_): but b has size 2x2

error: plt2vv: vector lengths must match

This usually occurs if we try to plot a pair of x and y data that are not the same size. See the example below.

In [26]:
t = 1:2:10; %time vector goes 1 3 5 7 9, having length 5
y = 1:10; %y vector goes  1 2 3 4 5 6 7 8 9 10, having length 10

plot(t,y)
error: __plt2vv__: vector lengths must match
error: called from
    __plt__>__plt2vv__ at line 489 column 5
    __plt__>__plt2__ at line 248 column 14
    __plt__ at line 113 column 17
    plot at line 223 column 10

error: =: nonconformant arguments (op1 is 1x1, op2 is somethingx1)

This error often indicates that you are trying to set one element in a matrix equal to another variable that has many elements. See the example below:

In [27]:
%say we have a vector v
v = 0:.1:2;

%now we have some other vector q
q = zeros(1,10)

%now let's imagine we tried to set the third element in q to v
q(3) = v

%we get the error! What we COULD do is set the third element in q to v(3) .
q(3) = v(3)
q =

   0   0   0   0   0   0   0   0   0   0

error: =: nonconformant arguments (op1 is 1x1, op2 is 1x21)
q =

 Columns 1 through 8:

   0.00000   0.00000   0.20000   0.00000   0.00000   0.00000   0.00000   0.00000

 Columns 9 and 10:

   0.00000   0.00000

error: 'something' undefined near line 1 column something

This error means that I am attempting to use a variable in a calculation before it is defined. See the example below:

In [28]:
clear all
%say I try to perform a calculation that uses a variable "b." I have defined no such variable yet.
a = 2*b
%NOW I define b
b = 2
error: 'b' undefined near line 2 column 7
b =  2

error: subscripts must be either integers 1 to (2^31)-1 or logicals

In the "indexing" introduction, we mentioned that we can access parts of a matrix by specifying row and column. This error means that we're attempting to access a "partial row" or "partial column" of a matrix. See the example below:

In [29]:
a = [1 2 3]
%this works:
a(2)
%but this does not.
a(.2)
%and neither does this, since there is no 0 index in matlab
a(0)
a =

   1   2   3

ans =  2
error: a(0.2): subscripts must be either integers 1 to (2^31)-1 or logicals
error: a(0): subscripts must be either integers 1 to (2^31)-1 or logicals

This error is also common if you forget to include a * between two parenthetical quantities you were trying to multiply. See the example below:

In [30]:
a = 1;
b = 2;
c = 3;

%this won't work!
d = c/((1+a)(2.3+b))

%but this will!
d = c/((1+a)*(2.3+b))
error: index (4.3): subscripts must be either integers 1 to (2^31)-1 or logicals
d =  0.34884

parse error or syntax error:

Parse errors are hard to track down, but they usually mean that you have typed something that Octave doesn't know how to interpret. An example is given below:

In [31]:
a = 2
1$
a =  2
parse error:

  syntax error

>>> 1$
     ^

Syntax errors are also common if you are missing a parenthesis, or if you have an extra one! See the example below.

In [32]:
a = 2;
b = 3;
g = 10;

(a+2))
parse error:

  syntax error

>>> (a+2))
         ^

In [ ]: