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 Answer

Commonmark migration
Source Link

#Matlab

Matlab

Snippet 20 - back to polynomials

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

###Snippet 20 - back to polynomials p=poly(r);cp=poly(A) WantWant 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).

#Matlab

###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).

Matlab

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).

Fixed spellings and simplified links
Source Link
Toby Speight
  • 7k
  • 1
  • 30
  • 43

elliptic curve elliptic curve

herehere

There are people who absolutely love this function. This basically just searches a minimum of fun with an initalinitial value x0 (can be a vector) without any conditinonsconditions 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.

without unwrapwithout unwrap with unwrapwith unwrap

Of course there are built in methods (like dot), but with the matrix-transformation opertoroperator ' 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.

linreglinreg

That is how to plot a graph. graph should contain a square adjecencyadjacency 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')

graphgraph (I declare this as modern art.)

This is one of the most awesomest functions, simple but useful. If you want to plot a real valued function depedingdepending 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...)

meshmesh

Take a vector x=-3:0.5:3 and and let plot do the rest. TherThere 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 argumetargument: 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. plotplot

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 usefulluseful for math functions (e.g. plotting) and you can define them in one line. But one backdrawdrawback 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 eastereggeaster egg if you type why in the console: They made a huge function that produces random messages like:

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

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 easteregg=easter egg=)

spy on identityspy on identity spy eastereggspy easteregg

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 codegolfingcode golfing. You want all possible products of the entrysentries of a and b? kron(a,b), here you go.

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 charactersiticcharacteristic 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 fastesfastest algorithm to perform this inversion-multiplication! (See e.g. here here)

But you can also use it for under- or overdefinedover-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.

Ok that does not look like much, but it is a very convenient tool: Matrix concatenation. A comma between two expresssionsexpressions 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?)

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 marticesmatrices (2d-arrays) which usis sooo damn usefulluseful 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 nonzeronon-zero elements) and have some kind of symmetry. ThatsThat's why you can easily 'compose' the matrix you need.

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 stepsizestep size, like 0:0.5:10 or so.

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.

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 opensourceopen 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 builtinbuilt-in parallelization methosmethods, 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, youreyou'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.)

elliptic curve

here

There are people who absolutely love this function. This basically just searches a minimum of fun with an inital value x0 (can be a vector) without any conditinons 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.

without unwrap with unwrap

Of course there are built in methods (like dot), but with the matrix-transformation opertor ' 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.

linreg

That is how to plot a graph. graph should contain a square adjecency 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.)

This is one of the most awesomest functions, simple but useful. If you want to plot a real valued function depeding 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

Take a vector x=-3:0.5:3 and and let plot do the rest. Ther 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 argumet: 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

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 usefull for math functions (e.g. plotting) and you can define them in one line. But one backdraw 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 easteregg if you type why in the console: They made a huge function that produces random messages like:

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

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 easteregg=)

spy on identity spy easteregg

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 codegolfing. You want all possible products of the entrys of a and b? kron(a,b), here you go.

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 charactersitic 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 fastes algorithm to perform this inversion-multiplication! (See e.g. here)

But you can also use it for under- or overdefined 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.

Ok that does not look like much, but it is a very convenient tool: Matrix concatenation. A comma between two expresssions 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?)

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 martices (2d-arrays) which us sooo damn usefull 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 nonzero elements) and have some kind of symmetry. Thats why you can easily 'compose' the matrix you need.

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 stepsize, like 0:0.5:10 or so.

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.

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 opensource 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 builtin parallelization methos, 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, youre 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.)

elliptic curve

here

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.

without unwrap with unwrap

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.

linreg

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.)

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

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

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:

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

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

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.

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.

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?)

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.

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.

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.

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.)

Post Made Community Wiki by Dennis
added 399 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253

Snippet 26 - iterate over matrices

Snippet 26 - iterate over matrices

Snippet 26 - iterate over matrices

Snippet 26 - iterate over matrices

added 399 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
edited body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
added 378 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
added 620 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
added 168 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
deleted 10 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
Loading
added 7 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
added 513 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
edited body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
edited body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
edited body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
added 315 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
added 315 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
added 513 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
added 513 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
added 989 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
added 649 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
added 1063 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
added 458 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
added 374 characters in body
Source Link
flawr
  • 44.1k
  • 7
  • 109
  • 253
Loading
1
2

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