Often you’ll have a need for recording the data your programs generate. MATLAB and Octave have a few ways to do this. We can best show this with a quick example.

The following code will generate a matrix 10,000 by 6. On my current hardware this takes about 2 seconds to execute.

% Sample code to generate a large matrix
clear 
 
for i = 1:10000
	a = sin(i*pi/180);
	b = cos(i*pi/180);
	c = tan(i*pi/180);
	temparray(i, 1:6) = [a, b, c, a^2, b^2, c^2];
end

In MATLAB and Octave, the process of outputting data to files is called “exporting.” Reading data in is likewise called “importing.”

The easiest way to save the above output to a file is to use the save function and add it directly to the code. Adding the following line just below the for loop would do the trick.

save test.txt temparray -ascii

The format is: save filename variable -format. The above will result in a text file called test.txt which will contain the variable “temparray.” You can open or view this in any text editor. The default delimiter is a space but if you’d like to save it as tab-delimited data, you would simply change the line to the following:

save test.txt temparray -ascii -tabs

If you do not specify the variable, all variables in the current workspace will be saved to the file. The above could also be executed from the command line, as long as you had recently run the code and the variable “temparray” was still assigned the value you need. Worth noting is that within Octave or MATLAB, if you save without using the -ascii tag, the default will be to save the data in a proprietary binary format and you will have something like the below text at the top of your document:

# Created by Octave 3.2.4, Thu Mar 10 00:24:15 2011 EST
# name: temparray
# type: matrix
# rows: 10 000
# columns: 6
1.7452e-02   9.9985e-01   1.7455e-02   3.0459e-04   9.9970e-01   3.0468e-04
3.4899e-02   9.9939e-01   3.4921e-02   1.2180e-03   9.9878e-01   1.2195e-03
5.2336e-02   9.9863e-01   5.2408e-02   2.7391e-03   9.9726e-01   2.7466e-03
...

This may be inconvenient for your purposes (for example, if you are using the data with an external program), but if you are going to use the “load” command (described later) to import this file, it doesn’t matter that this header information is present. If it is a hindrance, you can always save the data using the -ascii tag.

Other ways to export data to a file is with the fwrite, csvwrite and dlmwrite commands. Both programs have detailed help files on these commands but in short, they are for appending to files (fwrite), saving as comma-separated-values (csvwrite) and using specific delimiters (dlmwrite).

 

The following is the 4th problem in the Project Euler series. To date, it has been solved 77,499 times.

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

The following is a MATLAB/Octave solution.

% ProjectEuler.net problem #004
% Find the largest palindromic number that
% is a product of two three digit numbers
% Below code executed in 0.46925 seconds.
 
clear
tic();
 
% First, assume the answer will be two numbers between 900 and 999.
% If this doesn't find one, you could start at 800, then 700, etc.
% Make an array of all these multiples. Will be 10,000 elements
 
i=1;
for a = 900:999
	for b = 900:999
		new(i,1)=a*b;
		i=i+1;
	end
end
 
len = length(new)
 
temp = num2str(new);	% convert elements to strings
temprev = fliplr(temp);	% flip each element
 
index = temp == temprev; % compare the normal string to flipped string
 
% index is now an array, 10,000 x 6, of zeros and ones.
% Where all six in a row are ones, this number is the
% same forwards and backwards (temp = temprev).
% This will be the palindrome, ie., the answer.
 
for j = 1:len
	if index(j,1:6) == ones(1,6)
		max_index = j;
	end
end
 
max_element = max_index
final_answer = temp(max_index, 1:6)
exec_time = toc()

There you have it. Probably not the most efficient way to find the answer but it still executed in less than half a second.

 

This is the simplest problem yet and can be solved in MATLAB/Octave with one line of code. As of this writing, 83,275 people have solved this one. The problem states:

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

The below code returned the answer in 0.028778 seconds:

% ProjectEuler.net problem #003
% Find the largest prime factor of 600,851,475,143
% this is trivial in Matlab or Octave
% Below code executes in 0.028778 seconds.
 
clear
t = clock;
maximum = max(factor(600851475143))
exec_time = etime(clock, t)

There you have it. The built-in function factor returns a vector of all the factors of the argument. Of course max just plucks the maximum value out of that vector.

 

Problem 2 of Project Euler follows. As of this posting, there have been 113,666 correct answers posted.

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Here’s the MATLAB/Octave code I used to solve the problem. This executed in 0.010 seconds on my computer.

% ProjectEuler.net problem #002
% sum all even Fibonacci numbers below 4 million
 
clear
t = cputime;
 
% create array of Fibonacci numbers
a=0; b=1; c=0; i=1; j=0; newsum=0;
 
while c < 4e6
	c=a+b;
	a=b;
	b=c; 
	fib(i,1) = c;
	i=i+1;
end
 
disp('=================');
len = length(fib)
second_to_last = fib(len-1,1)
last = fib(len,1)
sum_of_fib = sum(fib)
disp('=================');
 
% parse the even numbers out of the array
 
for j = 1:len-1
	if rem(fib(j,1),2) == 0
		newsum(j,1) = fib(j,1);
	else
		newsum(j,1) = 0;
	end
end
 
sum_of_even = sum(newsum) # This outputs the answer.
exec_time = cputime-t # This is how long it takes to execute.

I typically try to avoid too many loops in my coding, but in this problem it didn’t slow it down much at all. Probably because there are only 33 numbers in the Fibonacci sequence that are below 4 million. I ran the code again for the sum of all even Fibonacci numbers below 4 Billion and there was no change at all in the execution time. This is actually intuitive when you realize that there are still only 47 Fibonacci numbers in the sequence below 4 billion – so the code only had to loop an extra 14 times.

What about summing all the numbers less than 4 Trillion?? Still only 61 numbers to loop through. Execute time was still 0.01 seconds. Here’s a quick table showing the results of running this code with three different upper limits. Note, the last digits are approximations.

Upper Limit, Fibonacci Numbers, Sum of all Even
4,000,000           33            4,613,000
4,000,000,000       47        1,485,600,000
4,000,000,000,000   61    2,026,400,000,000

There you have it. Happy coding!

 

The following is the first problem of Project Euler. To date, it has been solved by 136,521 users, most using C/C++.

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

The following is my solution in MATLAB/Octave. It’s a fairly simple problem and the solution is just a few lines of code. It basically uses a loop from 1 to 999 (note the problem states below 1000). We then take that number and divide it by 3 or 5 – if the remainder is zero, we know that number is a multiple of 3 or 5. The sum variable simply adds up all of these multiples. I used an fprintf statement to check the results while writing this, but commented it out to get the final result.

% ProjectEuler.net problem #001
 
sum = 0;
 
for i = 0:999
	if rem(i,3) == 0 | rem(i,5) == 0
		sum = sum + i;
	end
 
%fprintf('i: %3.0f sum: %4.0f \n', i, sum);
 
end
sum

There it is. I’m sure it could be cleaned up to be just a couple lines of code, but short code wasn’t the intent here. Efficiently getting the right answer was. Besides, it only took about 0.160 seconds to execute. Just for fun, I ran the code summing all the multiples of 3 and 5 below 100,000 and the code took about 14 seconds to execute. The answer was of the order of 2.3 billion (2,330,000,000).

 

I recently came across a very interesting problem solving site. It’s called Project Euler (usually pronounced Oiler) and it looks like it has been around for several years. The concept is simple. The administrators post problems to solve. The problems are typically math/science based and most require some type of programming language to solve. Users try to solve problems (in their language of choice) and are credited when they post a correct answer.

The site keeps track of the basic stats – like which problems and how many you have answered, as well as how many other users have successfully answered each problem. Also interesting is the number of users and what languages they are using. It was interesting to see that C/C++ seems to be the language of choice (with over 14,000 users as of this posting). The next most popular were Python (13,000 users), Java (8,600) and C# (4,600). MATLAB and Octave had about 1,000 users.

One of the coolest features of the site is that once you’ve solved a problem, you get access to their solution (in pdf) and the bulletin board to see many of the other solvers’ solutions. For example, if you’re a C++ programmer, you can learn several other approaches on how to solve the same problem. Since there aren’t too many users of MATLAB or Octave on the site, I didn’t see any other users’ code for solving the problems in these languages. So I’ve decided it might be beneficial to post my code here.

One last note, if you’re participating in the project, don’t worry about me revealing the answers here. I’ll try my best not to. If I do on occasion, don’t get all worked up, just try not to violate the spirit of the project. The site exists for fun – to practice coding, learn from others, and perhaps share your own knowledge. I realize that most of us in this game are in it because we find it interesting. We like seeing a problem, figuring out a way to solve it, and then coding a solution to solve it.

If you haven’t seen the site, I encourage you to check out Project Euler. It’s pretty fun, but be careful. For true geeks, it can be addictive. Good luck and happy coding!

 

In the last section we looked at how to execute some simple commands directly from the command line. Now we’re going to look at how to execute multiple commands by saving a series of simple commands in a file. Basically, we’re just writing a simple program and executing it from the command line.

We’ll start with a program that creates a plot of 100 random numbers.

Using your favorite plain text editor, copy the following code in it. On Linux I use gedit, which is probably the most ubiquitous, easy-to-use editor out there. If you’re coding in MATLAB on a Windows machine, you may be using Notepad or Editpad. Any plain text editor (that saves in ASCII format) will work.

% Random number plot
 
total_nums = 100;
rand_nums = rand(total_nums,1);
 
my_axis = [1:total_nums];
plot(my_axis,rand_nums), axis([0,total_nums,-1,2]);

Save the file as anything you want with a .m extension. I saved it as randnums.m. You can save it in any directory, but I like to keep a tidy file structure so in my main directory I keep a folder called CODE and under that Continue reading »

 

The MySQL command for selecting the maximum value from a column in a table is straightforward. First, here’s how you do it from a command line (or PHPmyAdmin) in MySQL.

For the following example, I have a database called weight_db and in that database a table called my_weight. There are several fields in this table, one if which is called wt and contains weight data. This is the column I want to select the maximum value from, using the max command.

mysql> use weight_db;
Database changed
mysql> SELECT max(wt) FROM my_weight;
+---------+
| max(wt) |
+---------+
|     199 |
+---------+
1 row in set (0.00 sec)

So, it’s simple and straightforward within MySQL. To do anything with this data in PHP is still fairly simple, it just requires another step. Continue reading »

© 2012 mattoneal.com Suffusion theme by Sayontan Sinha