Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

Return to Revisions

30 of 30
Commonmark migration

Matlab

Snippet 26 - iterate over matrices

This is something I just recently discovered. Usually you iterate over a given vector in for loops. But instead of vectors, you can also use matrices (rand(10) produces a 10x10 matrix with uniformly distributed numbers between 0 and 1).

for k=rand(10);disp(k);end

This then displays one column vector of the random matrix per iteration.

Snippet 25 - easy plotting

We know plotting is easy in matlab, but there is a super easy function ezplot (E-Z get it? It took quite a while until I finally got it, as I spelled Z always as sed instead of c, whatever...) Everyone likes elliptic curves:

ezplot('y^2-x^3+9*x-10.3')

elliptic curve

Snippet 24 - integration

The old fashioned word (but still in use in numerical computation) for integration is 'quadrature', can you guess what the result of the following one is?

quad(@(x)4./(1+x.^2),0,1)

Snippet 23 - images

Of course Matlab is also very popular among scientists who have to work with images (e.g. medical image analysis), so here is a very handy function. First argument is the image, second the angle and the third optional argument here tells the function to crop it to original size.

imrotate(rand(99),9,'c')

here

Snippet 22 - music

load handel;sound(y,Fs)

It will sound about like this (youtube link)

Snippet 21 - differentiate & integrate

polyint(polyder(p),c)

You can easily differentiate and integrate polynomials by using those two functions. When integrating, you can pass a second argument that will be the constant.

Snippet 20 - back to polynomials

p=poly(r);cp=poly(A)

Want the polynomial with the roots in r? Easy: p=poly(r). Want the characteristic polynomial of a matrix A? Easy: cp=poly(A). So roots(p) is exactly r (or a permutation of r).

Snippet 19 - another magic trick

fminsearch(fun,x0);

There are people who absolutely love this function. This basically just searches a minimum of fun with an initial value x0 (can be a vector) without any conditions on fun. This is great for fitting small models where you cannot (or you are too lazy) to differentiate the error/penalty/objective function. It uses the Nelder-Mead simplex algorithm which is pretty fast for functions where you cannot make any assumptions.

Snippet 18 - intro to polynomials

p=polyfit(x,y,deg)

Matlab has a nice solution for coping with polynomials. With polyfit you get a least squares polynomial of degree deg that approximates the points in x,y. You get a vector p that stores the coefficients of the polynomials, because that is the only thing what you need for representing a polynomial. If you go back to snippet 15, you can do the same thing by writing c = polyfit(x,y,2). So e.g. [1,-2,3] represents the polynomial x^2 - 2*x+3. Of course there are also functions for fitting other elementary, or arbitrary functions.

Snippet 17 - angles and discontinuities

unwrap(angle(c))

If you want to get the argument of a 'continuous' vector of complex numbers you often get back values that seem to have a discontinuity. E.g. angle([-1-0.2i,-1-0.1i,-1,-1+0.1i,-1+0.2i]) will get you [-2.94,-3.04,3.14,3.04,2.94] since angle only returns angles between -pi and pi. The function unwrap will take care of this! If you get a discontinuity like this, it will just add a multiple of 2*pi in order to remove those: '[-2.94,-3.04,-3.14,-3.24,-3.34]' This even works for 2d-matrices! If you just plot the argument of complex numbers with a negative real part you get the first graphics you'll get the first image, with unwrap you get the second one:

without unwrap with unwrap

[x,y] = meshgrid(-1:0.01:0,-0.5:0.01:0.5);
z = x+i*y;
imagesc(angle(z))
imagesc(unwrap(angle(z)))

Snippet 16 - scalar product

[1;2;3]'*[4;5;6]

Of course there are built in methods (like dot), but with the matrix-transformation operator ' it is as simple as that. If you do not know whether you have row or column vectors, you can just use a(:)'*b(:) where a(:) always returns a column vector.

Snippet 15 - linear least squares, the ugly method with the magic wand

[x.^2,x,x.^0]\y

x is the (column) vector with the values on the x-axis, y the noisy y-values. Type c=[x.^2,x,x.^0]\y and you get the coefficients of the 2nd degree polynomial. Of course you can use one of the billion builtin fit functions of matlab (how boring) why not use the magic wand?=)

x = (-1:0.1:2)';
y = 3*x.^2-2*x+1+randn(size(x)); %add some gaussian (normal) noise
A = [x.^2,x,x.^0];
c = A\y %output: c = ]3.0049; -2.3484; 1.1852]
plot(x,y,'x',x,A*c,'-')

linreg

Snippet 14 - graphs

gplot(graph,x)

That is how to plot a graph. graph should contain a square adjacency matrix and x should be a nx2 matrix that contains the coordinates of each node. Lets make a random graph: graph = triu( rand(8)>.7) (make a Matrix that contains 0s and 1s, get only the upper triangle for an interesting graph). x = rand(8,2) then plot with some fancy styles gplot(graph,x,'k-.d')

graph (I declare this as modern art.)

Snippet 13 - meshgrid

meshgrid(a,b)

This is one of the most awesomest functions, simple but useful. If you want to plot a real valued function depending on two variables, you can just define a vector of values for the x-axis and one for the y-axis (a and b). Then with meshgrid, you can create two matrices of the size len(a) x len(b) where one has only the vector a as column, and the other has only the column has only the vectors b as rows. Usage example:a = -3:0.2:3;[x,y]=meshgrid(a) (if both vectors are the same, it is sufficient to just pass one.) Then you can just type z=x.^2+-y.^2 and e.g. mesh(x,y,z). This works for an arbitrary number of dimensions! So this is not only great for plotting, but also for getting all possible combinations of different vectors etc... (So, if you want to create a new code golf language, this should be in there, just make sure you use a shorter function name...)

mesh

Snippet 12 - plotting

plot(x,x.^2)

Take a vector x=-3:0.5:3 and and let plot do the rest. There are many more functions for plotting this is just a very basic one that you can use all the time. It would be already enough to write plot(v) and the data in v will be plotted against the array indices. How simple is that? If you want to style your plot, just add a string as a third argument: e.g. 'r:o' will make a red, dotted line with circles around the data points. If you want multiple plots, just add more arguments, or use matrices instead of vectors. Foolproof. plot

Snippet 11 - function handles

f=@(x,y)x+y

This is an example of a function handle that gets stored in f. Now you can call f(1,2) and get 3. Function handles in matlab are very useful for math functions (e.g. plotting) and you can define them in one line. But one drawback is that you cannot have conditionals or piecewise (and therefore no recursion). If you want this, you have to use the function statement and declare a new function, and each of those has to be stored in a separate file... (WHYYYYYY????)

PS: You'll get another funny easter egg if you type why in the console: They made a huge function that produces random messages like:

The tall system manager obeyed some engineer.
The programmer suggested it.
It's your karma.
A tall and good and not excessively rich and bald and very smart and good tall and tall and terrified and rich and not very terrified and smart and tall and young hamster insisted on it.

...which is very comforting if you are desperate enough to ask the console why...

Snippet 10 - How does my matrix look?

spy(eye(9))

As you know by now eye(9) creates a 9x9 identity matrix. spy just creates a that shows the zero/nonzero entries of the matrix. But you can also use it for displaying any binary 2d data. If you call spy without argument you'll get a nice little easter egg=)

spy on identity spy easteregg

Snippet 9

kron(a,b)

The kron function evaluates the Kronecker product of two matrices. This is very useful for discretisized multidimensional linear operators. I also used it every now and then for code golfing. You want all possible products of the entries of a and b? kron(a,b), here you go.

Snippet 8

5*a\b.*b

Ok here I mixed up 3 different operator. You can multiply any matrix by a scalar by just using *. (Then every entry of the matrix gets multiplied by that scalar). But * also performs matrix multiplications. If you prepend a dot you get the .* operator, this one multiplies two matrices of the same size but entry wise. (This can also be done with division operators like / and \.)

Next, the backslash operator can be used as left division (in contrast to / which performs right division as you are used to) but it is also the most powerful and characteristic operator of matlab: It performs a 'matrix division'. Lets say you have the system of linear equations A*x=b and you want to solve it for x, then you can just type x=A\b. And \ (you can also use / but that is less common for matrices) first quickly analyzes the matrix, and uses the results to find the fastest algorithm to perform this inversion-multiplication! (See e.g. here)

But you can also use it for under- or over-defined systems (where the there exists no inverse or where the matrix isn't even square, e.g. for least squares method). This really is the magic wand of matlab.

Snippet 7

[a,b;c]

Ok that does not look like much, but it is a very convenient tool: Matrix concatenation. A comma between two expressions means that they get concatenated horizontally (that means they have to have the same height) and a semicolon means that the previous 'line' will be above the next 'line' (by line I mean everything between two semicolons. Just a simple example: a = [1,2;3,4]; b = [5;6]; c =[7,8,9]; d=[a,b;c]; will result in the same d as d=[1,2,5; 3,5,6; 7,8,9]. (Get it?)

Snipped 6

eye(7)

This function produces a full 7x7 identity matrix. It is that easy. There are other functions like nan,inf,ones,zeros,rand,randi,randn that work the very same way. (If you pass two arguments you can set the height/width of the resulting matrix.) As I will show later, you can easily create and (and in a very visual way) concatenate matrices (2d-arrays) which is sooo damn useful and easy if you have to numerically solve partial differential equations. (When you solve PDEs the general approach is discretisizig the derivative operators, basically you will get just a huge system of linear equations that needs to be solved. These matrices normally are sparse (only very few non-zero elements) and have some kind of symmetry. That's why you can easily 'compose' the matrix you need.

Snippet 5

a(a>0.5)

I hope you are not getting tired by all the ways of accessing arrays. This shows an easy way to get all elements of an array that meet some conditions. In this case you get a vector of all elements of a that are greater than 0.5. The expression a>0.5 just returns a matrix of the same size as a with ones for each element that satisfies the condition and a 0 for each element that doesn't.

Snippet 4

a(:)

This again just returns the contents of a as a column vector (nx1 matrix). This is nice if you do not know whether you stored your data as column or row vector, or if your data is two dimensional (e.g. for 2d finite differences methods).

Snippet 3

1:9

You can easily make vectors (in this case 1xn matrices) with the semicolon operator. In this case you get the vector [1,2,3,4,5,6,7,8,9]. This is also particularly nice for accessing slices of other vectors as e.g. a(2:4) accesses the second, third and fourth element of the vector a. You can also use it with a step size, like 0:0.5:10 or so.

Snippet 2

i;

A semicolon suppresses output to console. You can see it as a good or a bad thing, but I like it for debugging stuff. Any line of calculation etc. will automatically print its result to the console, as long as you do not suppress the output by a semicolon.

Snippet 1

i

Complex number are a basic number type. (Too bad many people use i as a counting variable in for loops in which case it gets overridden.)

Intro

For those who do not know, MatLab is a programming language (with nice IDE that is also called MatLab?) that is first of all intended for numerical calculations* and data manipulation. (There is an open source counterpart called "Octave") As it is only** interpreted it is not very fast, but it's strength are that you can easily manipulate matrices and many algorithms are implemented in an optimized way such that they run pretty fast when applied on matrices. It also is a very easy language to learn, but I do not recommend it as a starter language as you will assume pretty bad 'programming' habits.

*As it is a interpreted language it can be very slow for expensive projects, but you have built-in parallelization methods, and you can also use multiple computers together to run a program. But if you really wanna get fast I think you still depend on C or Fortran or crazy stuff like that. But still many implemented algorithms (matrix multiplication, solving systems of linear equations etc) are heavily optimized and perform quite well. But if you program the same algorithms in Matlab itself, you're gonna have to wait=) (Something really unintuitive when you come from other languages is that if you vectorize your operations instead of using for loops, you can save much time in Matlab.)

**You can sort of compile your programs, but that mainly converts the source code to an unreadable file (for humans), that is not that much faster when executed.

flawr
  • 44.1k
  • 7
  • 109
  • 253

AltStyle によって変換されたページ (->オリジナル) /