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 first objective in our familiarization tour with MATLAB and Octave is an understanding of the command window. Anyone who uses a Unix or Linux operating system with any regularity is probably already familiar with the command line.

Both languages do offer a similar graphical user interface for those who prefer the friendly windows-type environment. The MATLAB user interface is installed with the program whereas Octave uses QtOctave, developed by Pedro Luis Lucas Rosado.

As of this writing, the current version of QtOctave is 0.9.2 and is available at the project page: https://forja.rediris.es/projects/csl-qtoctave, or most likely for Linux users, from your distribution’s repositories. We’ll go into each of these in further detail in a later chapter, but for now will leave it at the fact that they are available.

While both GUIs are quite capable in their functionality, for some there is an intangible feeling they get from knowing how to perform operations and manipulate code from the basic command line. This is how I typically work and where I’d like to get started. Continue reading »

Basic Arithmetic using Matlab and Octave

 Uncategorized  Comments Off
Feb 142011
 

All basic arithmetic functions can be done directly from the command line. In this capacity, MATLAB can perform as a simple (or scientific) calculator. Try the following from the command line.

>> 3 * 6
ans = 18

MATLAB conveniently supplies the answer as a variable named ans. The answer to the last calculation you performed will always live in this variable. You can check this by simply typing ans on the command line. This is convenient but not often useful as we’ll normally define our own variables to the calculations we ask MATLAB to perform. We’ll talk more about variables later.

In both MATLAB and Octave, the standard arithmetic precedence applies. Multiplication and division have the same precedence and both take priority over addition and subtraction. Exponentiation has the highest priority. As in most languages, parentheses can used to group arithmetic functions. The below examples should make this point clear…

>> 3 * 4 + 4
ans =  16
>> 3 * (4 + 4)
ans =  24

Exponents are coded using the standard caret (^) character, sometimes pronounced colloquially as “to the” or even “hat” as the following may be read as “x to the y” or “x hat y.” We’ll define a couple of variables to highlight this. Continue reading »

 

This is one of the simplest snippets of code for simulating a random coin toss. It has Matlab (or Octave) pull a random number, and based on that random number, return either a heads or tails. Very simple, but you may be surprised at how often this little loop can be used in game theory simulations. The code…

if rand < 0.5
  toss = 'heads'
else
  toss = 'tails'
end
disp('toss')

Of course, you could execute it directly from the command line. Just separate what would be the separate lines with commas. Below is the single line of code executed three times…

>> if rand < .5, 'heads', else, 'tails', end
ans = tails
>> if rand < .5, 'heads', else, 'tails', end
ans = heads
>> if rand < .5, 'heads', else, 'tails', end
ans = tails

There you have it. Happy coding!

© 2012 mattoneal.com Suffusion theme by Sayontan Sinha