viernes, 9 de diciembre de 2011

RESOLUCION DE ECUACIONES LINEALES EN MATLAB

Hay muchas maneras diferentes de resolver sistemas de ecuaciones lineales. We can classify them as: Podemos clasificar como:
1) Direct methods 1) Los métodos directos
In this category we can list the various row reduction algorithms available. En esta categoría se pueden enumerar los algoritmos de reducción de la fila varias disponibles. Most of these algorithms can be easily programmed in a basic programming language such as C++. La mayoría de estos algoritmos pueden ser fácilmente programado en un lenguaje de programación básicos como C + +. They can also be programmed in MATLAB and there are various software libraries, which contain superb programs and functions for the solution of linear systems. También se puede programar en MATLAB y hay varias bibliotecas de software, que contienen los programas de soberbia y funciones para la solución de sistemas lineales.
In order to have an idea about these methods we will go over a very simple example using the upper triangularization technique. Con el fin de tener una idea acerca de estos métodos vamos a ir sobre un ejemplo muy sencillo utilizando la técnica de triangulación superior.
Consider the system A x = B with Consideremos el sistema A x = B con
  
as a first step we form the “ augmented matrix ” by placing B as the fourth column of A. We then proceed to add ( or subtract) appropriate multiples of the first equation from the other two so that the numbers in locations 2,1 and 3,1 of the matrix become zero. como un primer paso se forma la "matriz aumentada" mediante la colocación de B como la cuarta columna de la A. A continuación, procederá a sumar (o restar) en múltiplos de la primera ecuación de los otros dos para que los números en los lugares 2,1 y 3,1 de la matriz se convierten en cero. We should only remember the basic properties of equality, to convince ourselves that this type of algebraic manipulation does not alter the roots of the system. Sólo debemos recordar las propiedades básicas de la igualdad, para convencernos de que este tipo de manipulación algebraica no altera las raíces del sistema. In other words, the system obtained after these row operations has the same roots as the original system, as we say, it is equivalent . En otras palabras, el sistema obtiene después de estas operaciones fila tiene las mismas raíces que el sistema original, como se suele decir, es equivalente. We proceed with the row reduction until the coefficient matrix becomes triangular . Se procede a la reducción de la fila hasta que se convierte en la matriz de coeficientes triangular.
We can now solve the system easily by performing a backward substitution . Ahora podemos resolver el sistema con facilidad mediante la realización de una sustitución hacia atrás. What we mean is this: first solve the last equation for x 3 to obtain Lo que queremos decir es esto: en primer lugar resolver la última ecuación para obtener x 3
x 3 = 3 / 7, x 3 = 3.7,
then use the second equation to obtain x 2 as a continuación, utilizar la segunda ecuación para obtener x 2,
x 2 = (2 / 7) * ( 3 / 2 (-7 / 2 ) * x 3 ) = 6 / 7, x 2 = (2 / 7) * (3 / 2 (-7 / 2) * x 3) = 07.06,
and finally use the first equation to obtain x 1 as y, finalmente, el uso de la primera ecuación para obtener x 1 como
x 1 = (1 / 2) * ( 1 (-1) * x 2 3 * x 3 = 2 / 7. x 1 = (1 / 2) * (1 (-1) * x * 2 3 x 3 = 2.7.
The corner elements of the upper triangular matrix ( the ones on the diagonal) are called pivot elements. Los elementos de la esquina de la matriz triangular superior (los de la diagonal) se denominan elementos de pivote. The larger the absolute value of these elements , relative to the other elements of the row, the more stable the solution is. Cuanto mayor sea el valor absoluto de estos elementos, en relación con los otros elementos de la fila, el más estable es la solución. Some solution methods exchange the order of equations in order to achieve the maximum pivot elements. Pivoting is actually strongly recommended for any serious program designed for the solution of linear systems of equations. Algunos métodos de solución de intercambio del orden de las ecuaciones con el fin de lograr los elementos de giro máximo. Pivotante en realidad es muy recomendable para cualquier programa serio diseñado para la solución de sistemas de ecuaciones lineales.
For completeness we should mention Cramer's Rule , which utilizes determinants for the solution of systems. Determinant is a number associated with a square matrix. Para completar cabe mencionar la regla de Cramer, que utiliza los factores determinantes para la solución de sistemas. Determinante es un número asociado a una matriz cuadrada. We will not learn here how to calculate determinants by hand, but MATLAB gives the determinant of a matrix by the use of the command det(a). See the example below: No vamos a aprender aquí la forma de calcular los factores determinantes a mano, pero MATLAB ofrece el determinante de una matriz por el uso del comando det (a) Véase el siguiente ejemplo.:
Cramer's rule produces the solution of a system A x = B as follows: La regla de Cramer produce la solución de un sistema A x = B de la siguiente manera:

The first unknown is given by La primera incógnita está dada por
x1 = det( A1 ) / det( A ) x1 = det (A1) / det (A)
The second by El segundo por
x2 = det( A2 ) / det( A ), x2 = det (A2) / det (A),
The third by El tercero, por
x3 = det( A3 ) / det( A ), x3 = det (A3) / det (A),

And so on…. Y así sucesivamente .... Here A1 is the matrix obtained by replacing the first column of A by B , A2 is the matrix obtained by replacing the second column of A by B etc…. Aquí A1 es la matriz que se obtiene mediante la sustitución de la primera columna de A por B, A2 es la matriz que se obtiene mediante la sustitución de la segunda columna de A por B, etc .... It is easy to see that if det( A ) is zero or close to zero we get into trouble. Es fácil ver que si det (A) es igual a cero o cercano a cero nos metemos en problemas. Well posed engineering problems avoid this type of “ill conditioning” . Bien planteado problemas de ingeniería evitar este tipo de "condicionamiento enfermo".
2) Iterative methods 2) Los métodos iterativos
There are various methods in this category. Existen varios métodos de esta categoría. The general idea is that we start with an arbitrary guess for the solution and then we use the equations to progressively improve the solution ( very much like Newton's method). La idea general es que comencemos con un valor arbitrario para la solución y luego utilizar las ecuaciones de mejorar progresivamente la solución (muy parecido a el método de Newton). The most popular and in fact easy method is the Gauss Siedel method of iteration. El método más popular de hecho y de fácil es el método de Gauss Siedel de iteración. Here each equation is solved for one of the unknowns in terms of the remaining ones, then using the initial guess a new solution is obtained which is , in turn, substituted into the equations to yield an improved estimate and so on.. Aquí cada ecuación se resuelve para una de las incógnitas en cuanto a los restantes, a continuación, utilizando la conjetura inicial de una nueva solución que se obtenga, a su vez, sustituido en las ecuaciones para obtener una estimación mejorada, etc .. We give an example below: Damos un ejemplo a continuación:
Consider again the system A x = B with Consideremos de nuevo el sistema A x = B con
. .
We write: Escribimos:
x 1 = ( 1 + x 2 3 * x 3 ) / 2 …….. x 1 = (1 + x 2 3 * x 3) / 2 ... ... .. eq. eq. 1 1
x 2 = ( 2 x 1 + 2 * x 3 ) / 3 …….eq. x 2 = (2 x 1 + 2 * x 3) / 3 ... .... eq. 2 2
x 3 = ( 3 3 * x 1 ) / 5 ………….eq. x 3 = (3 * 3 x 1) / 5 ... ... ... .... eq. 3 3
Now we start with the initial guess [0, 0, 0] and using equation (1) we obtain [ 0.5, 0, 0] . Ahora empezamos con la estimación inicial [0, 0, 0] y usando la ecuación (1) se obtiene [0.5, 0, 0]. Using this in equation (2) we obtain [ 0.5, 0.5, 0] and using this in equation (3) we obtain [0.5, 0.5, 0.3]. El uso de este en la ecuación (2) se obtiene [0.5, 0.5, 0] y el uso de esto en la ecuación (3) se obtiene [0.5, 0.5, 0.3]. We now go back to equation (1) and obtain [0.3, 0.5, 0.3] repeating this cycle produces the approximations shown ( obtained using excel): Volvemos a la ecuación (1) y obtener [0,3, 0,5, 0,3] repitiendo este ciclo produce las aproximaciones se muestra (obtenida usando Excel):
We can check and see that the unknowns converged well ( four significant digits) to the “exact” values: [ 2 / 7, 6 / 7, 3 / 7 ] . Podemos comprobar y ver que las incógnitas convergentes bien (cuatro dígitos significativos) a la "exacta" de los valores: [2.7, 6.7, 7.3].
3) Piece of cake methods 3) Pieza de los métodos de la torta
Here we use a package to obtain the solution of the system. Aquí se utiliza un paquete para obtener la solución del sistema. This package may be MAPLE, it could be Excel, but the ideal one is MATLAB. Este paquete puede ser MAPLE, podría ser Excel, pero el ideal es MATLAB.
The command for solving the system A x = B is simply x = El comando para resolver el sistema A x = B es simplemente x = A \ B. The following picture demonstrates this: A B. \ El cuadro siguiente muestra esto:
The inverse of a matrix: La inversa de una matriz:
A special square matrix is the “identity ” matrix. Un especial de matriz cuadrada es la "identidad" de la matriz. This matrix has 1's seating on each place of its main diagonal, and zero everywhere else. Esta matriz tiene un asiento en cada lugar de su diagonal principal y cero en cualquier otro lugar. For example the 3X3 identity matrix is: Por ejemplo, la matriz de identidad 3x3 es la siguiente:
Now we can pose the following problem:” If a nXn square matrix A is known, can we find a matrix A -1 so that Ahora podemos plantear el siguiente problema: "Si un nXn matriz cuadrada A es conocido, podemos encontrar una matriz A -1 para que
AA -1 = identity matrix . AA -1 = matriz identidad.
The matrix A -1 is called the inverse of A . La matriz A -1 se llama la inversa de A. If you think carefully you will see that the columns of the inverse are obtained by solving n systems of equations which have the form Si lo piensas detenidamente, verá que las columnas de la inversa se ​​obtienen mediante la resolución de sistemas de ecuaciones n que tienen la forma
A x = d A x = d
With d being the individual columns of the identity matrix. Con d ser una de las columnas de la matriz de identidad.
Thinking again carefully you will see that the solution of a system of equations A pensar de nuevo con cuidado, verá que la solución de un sistema de ecuaciones
A x = B , A x = B,
c an be formally written as: c una manera formal por escrito como:
x = A -1 B x = A -1 B
( ( this is the sequence:) Esta es la secuencia:)
A x = B A x B =
A -1 A x = A -1 B A -1 x A = A -1 B
Identity x = A -1 B Identidad x = A -1 B
x = A -1 B x = A -1 B
Of course MATLAB calculates the inverse with extreme ease. Por supuesto MATLAB calcula la inversa con extrema facilidad.
 El presente tutorial se ocupa exclusivamente de métodos numéricos para resolver ecuaciones algebraicas y trigonométricas, tanto individuales como de manera simultánea, tanto lineales como no lineales.   Analytical solutions can be obtained using the methods described in the symbolic tutorial . Soluciones analíticas se puede obtener mediante los métodos descritos en el tutorial simbólico .    When both symbolic and numerical methods work, sometimes one is simpler and sometimes the other. Cuando ambos métodos simbólicos y numéricos de trabajo, a veces uno es más simple y, a veces el otro.
In order to benefit from the following material one must copy and paste the indicated commands into MATLAB and execute them. Con el fin de beneficiarse de los siguientes materiales se debe copiar y pegar los comandos indicados en MATLAB y los ejecuta.   These commands are shown in the format >> help plot , for example. Estos comandos se muestran en el formato> plot ayudar a>, por ejemplo.   The user should look up each command in MATLAB's help in order to understand the command and the different possible syntaxes that can be used with it. El usuario debe buscar cada comando en la ayuda de MATLAB con el fin de entender los comandos y la sintaxis posibles que se pueden utilizar con él.
Graphical solution of one non-linear equation or two non-linear equations in explicit form Solución gráfica de una ecuación no lineal o dos ecuaciones no lineales en forma explícita
When a single equation or a pair of equations is to be solved, it is good practice to first make a plot. Cuando una sola ecuación o un par de ecuaciones a resolver, es una buena práctica para hacer primero una parcela.   In this way, it can be seen immediately what the approximate solution is. De esta manera, se puede ver inmediatamente lo que la solución aproximada es.   
In order to plot an equation using the "plot" command it must be in the explicit form, ie y = f(x). Con el fin de trazar una ecuación utilizando el comando "plot" que debe ser en forma explícita, es decir, y = f (x).   If the equation can be written only in implicit form, ie f( x ,y ) = 0, then the " ezplot " command must be used as described in the symbolic tutorial . Si la ecuación se puede escribir sólo en forma implícita, es decir, f (x, y) = 0, entonces el "ezplot" comando debe ser utilizado como se describe en el tutorial simbólico .  
We consider first a single equation, ie f(x) = 0. Examinaremos en primer lugar una sola ecuación, es decir, f (x) = 0.   As an example we will use sin 2 (x) e -x/2 – 1 = 0. Como ejemplo vamos a utilizar sin 2 (x) e-x / 2 - 1 = 0.   Do the following steps: Siga los siguientes pasos:
  1. While optional, it's a good idea to clear the Workspace memory in order to avoid the chance of MATLAB using a previous value for a variable: Aunque opcional, es una buena idea para borrar la memoria de área con el fin de evitar la posibilidad de MATLAB con un valor previo de una variable:
            >> clear >> Claro
  1. Guess the range of x values over which you expect a solution and generate values for the x vector over this range. Supongo que el rango de valores de x en la que espera una solución y generan valores para el vector x en este intervalo.   Select an increment small enough to yield a smooth curve. Seleccione un incremento lo suficientemente pequeño como para producir una curva suave.   For example: Por ejemplo:
            >> x = -10:0.01:10; >> X = -10:0.01:10;
            gives x from -10 to +10 in increments of 0.01. da x -10 a 10 en incrementos de 0,01.
  1. Generate the y = f(x) vector corresponding to these x values: Generar y = f (x) vector que corresponde a estos valores de x:
            >> y = sin(x) .^ 2.*exp(-x/2) -1; .>> Y = sin (x) ^ 2 .* exp (-x / 2) -1;
Notice the dots before ^ and *. Observe los puntos antes ^ y *.   These dots are essential. Estos puntos son esenciales.   Because x is a vector, we must use array operations rather than scalar operations (without the dot). Debido a que x es un vector, debemos utilizar las operaciones de matriz en lugar de operaciones escalares (sin el punto).
  1. Also create a line for y = 0. También crear una línea de y = 0.   The intersection of this line with the curve above gives the solution (or solutions, as in this example). La intersección de esta línea con la curva de arriba da la solución (o soluciones, como en este ejemplo).   To do this we create a vector with the same number of values as x, with each value being 0. Para ello creamos un vector con el mismo número de valores x, y cada valor es 0.
            >> y0 = zeros( 1,length(x)); >> Y0 = zeros (1, la longitud (x));
  1. Make the plot: Hacer la trama:
            >> plot( x,y,x,y0); >> Plot (x, y, x, y0);
  1. Locate the solution(s). Localice la solución (s).   If the two lines do not intersect, repeat with another range for x. Si las dos líneas no se cruzan, repita con otro rango de x.   In our example, the lines intersect more than once, and we surmise, in fact, that there are infinitely many solutions for negative x. En nuestro ejemplo, las líneas se cruzan más de una vez, y suponemos que, de hecho, que hay una infinidad de soluciones para valores negativos de x.   Let us select the solution at about x = -1. Vamos a seleccionar la solución alrededor de x = -1.    Enlarge this area of the intersection in the Figure window by Tools / Zoom In, and then clicking near the intersection once or more. Aumentar esta área de la intersección en la ventana de la figura de Herramientas / Zoom In, a continuación, haga clic cerca de la intersección una vez o más.   Then go to Tools / Data Cursor. A continuación, vaya a Herramientas / cursor de datos.   Click as close as you can to the intersection. Haga clic lo más cerca posible a la intersección.   Write the result down to compare with that obtained by using the " fzero " command below. Escriba el resultado al comparar con la obtenida mediante el uso de la "fzero" comando a continuación.
Next let us consider a pair of explicit equations, y = sin 2 (x) e -x/2 – 1 and y = 10sin(x)/x. A continuación vamos a considerar un par de ecuaciones explícitas, y = sen 2 (x) e-x / 2 - 1 y = 10sin (x) / x.   Proceeding as above : Procedimiento que el anterior:
            >> clear ; >> Claro;   x = -10:0.01:10; x = -10:0.01:10;    y1 = 10*sin(x)./x; y1 = 10 * sin (x) / x.;    y2 = sin(x).^2.* exp (-x/2) - 1; y2 = sen (x) ^ 2 .* exp (-x / 2) - 1.;   plot (x,y1,x,y2); plot (x, y1, x, y2);
Again we see that there are many solutions (intersections), both positive and negative. Una vez más vemos que hay muchas soluciones (intersecciones), tanto positivos como negativos.   (Note that when MATLAB calculated sin( 0)/0 it gave a warning, but nonetheless completed the other calculations and the plot.) (Tenga en cuenta que cuando MATLAB calcula sin (0) / 0 le dio una advertencia, pero no obstante, completar los cálculos de otros y la trama.)   As above, find the approximate solution at x near 3.5. Como el anterior, encontrar la solución aproximada en cerca de 3,5 x.   (I get x = 3.49, y = 0.9796.) Write down your result to compare with those to be found later. (Me da x = 3.49, y = 0,9796). Anote su resultado para comparar con los que se encuentran más adelante.   Alternately, we can equate these two equations (since both = y), move everything to the left-hand side, and find the values of x when this is 0. Alternativamente, podemos igualar estas dos ecuaciones (ya que ambos = y), que todo se mueva a la izquierda, y encontrar los valores de x cuando esta es 0.    For the value of x found, the corresponding value for y is determined by substituting this back into either one of the original equations. Por el valor de x se utilizará el valor correspondiente para y se determina mediante la sustitución de esta de nuevo en cualquiera de las ecuaciones originales.
>> clear ; >> Claro;   x = -10:0.01:10; x = -10:0.01:10;    yeq = 10*sin(x)./x - sin(x).^2.* exp (-x/2)+1; yeq = 10 * sin (x) / x - sin (x) ^ 2 .* exp (-x / 2) 1..;
>> yeq0 = zeros( 1,length(x)); >> Yeq0 = zeros (1, la longitud (x));    plot(x,yeq,x,yeq0); plot (x, yeq, x, yeq0);
Using the same method as above, I again got x = 3.49 and yeq = 0. Usando el mismo método que el anterior, de nuevo tiene x = 3.49 y yeq = 0.    Note that yeq is not y. Tenga en cuenta que no es yeq y.   To find the y we substitute x back into both of the simultaneous equations, which gives us two results. Para encontrar el sustituto y que x en ambas ecuaciones simultáneas, lo que nos da dos resultados.   (Use your own value of x rather than my value of 3.49.) (Use su propio valor de x en lugar de mi valor de 3,49.)
            >> clear ; >> Claro;   x = 3.49; x = 3,49;   y1 = 10*sin(x)/x, y1 = 10 * sin (x) / x,    y2 = sin(x)^2* exp (-x/2) - 1 y2 = sen (x) ^ 2 * exp (-x / 2) - 1
The closer these are y1 and y2, the better our solution. Cuanto más cerca se trata de y1 y y2, mejor será nuestra solución.
Numerical solution of one or two non-linear equations in explicit form (y = f(x)) Solución numérica de una o dos ecuaciones no lineales en forma explícita (y = f (x))
We use the " fzero " command, which finds the value of x for f(x) = 0. Usamos el "fzero" de comandos, que encuentra el valor de x de f (x) = 0.   (See >> help fzero .) (Ver fzero>> ayuda.)   We will use the same examples as above. Vamos a utilizar los mismos ejemplos anteriores.   To display the result to 14 significant figures we first change the format to long. Para mostrar el resultado de 14 cifras significativas en primer lugar cambiar el formato a largo plazo.   For the single equation, sin 2 (x) e -x/2 – 1 = 0: Para la ecuación única, sin 2 (x) e-x / 2 - 1 = 0:
            >> clear ; >> Claro;   format long; formato largo;   x = fzero ('sin(x)^2*exp(-x/2)-1', -1) x = fzero ('sin (x) ^ 2 * exp (-x / 2) -1, -1)
(Notice that no dot is required now before ^ or *, although using the dot causes no problem.) (Tenga en cuenta que ningún punto que se requiere ahora antes ^ o *, aunque con el punto no causa ningún problema.)   How does this result compare to the approximate result you obtained by the graphical method above? ¿Cómo se compara este resultado con el resultado aproximado que ha obtenido por el método gráfico de arriba?
Now we again consider the pair of equations, y = sin 2 (x) e -x/2 – 1 and y = 10sin(x)/x: Ahora estamos de nuevo en cuenta el par de ecuaciones, y = sen 2 (x) e-x / 2 - 1 y = 10sin (x) / x:
            >> clear ; >> Claro;   x = fzero ('10*sin(x)/x - sin(x)^2* exp (-x/2) + 1', 3.5) x = fzero ('10 * sin (x) / x - sin (x) ^ 2 * exp (-x / 2) + 1 ', 3,5)
            >> y1 = 10*sin(x)/x, >> Y1 = 10 * sin (x) / x,    y2 = sin(x )^ 2* exp (-x/2) - 1 y2 = sen (x) ^ 2 * exp (-x / 2) - 1
As before, we see that the numerical method is more accurate. Al igual que antes, vemos que el método numérico es más preciso.   So why bother with the graphical method at all? Así que ¿por qué molestarse con el método gráfico en absoluto?   The reason is, to see about where you need to have " fzero " seek a solution! La razón es, para ver dónde es necesario tener "fzero" buscar una solución!
Finding a particular solution when there are infinitely many Encontrar una solución particular, cuando hay un número infinito
 
There are equations with an infinite number of solutions, for example sin(x) = 1/2. Hay ecuaciones con un número infinito de soluciones, por ejemplo el pecado (x) = 1 / 2.  
It is helpful to see some of these solutions by plotting y = sin(x) - 1/2 and then observing where y has values of zero: Es útil para ver algunas de estas soluciones por el trazado de y = sen (x) - 1 / 2 y luego la observación de donde y tiene valores de cero:
>> clear , >> Claro,   syms x; syms x;   eq ='y - sin(x) + 1/2'; eq = 'y - sin (x) + 1 / 2 ";   ezplot ( eq ,[-6,6,-2,1]) ezplot (eq, [-6,6, -2,1])
>> hold on; eq0='0'; ezplot ( eq0); hold off >> Conservar; eq0 = '0 '; ezplot (eq0); mantener a raya
The "hold on" command tells MATLAB to write the subsequent plots on top of the first one, rather than replacing it. El "sobre" comando le dice a MATLAB para escribir las parcelas posteriores en la parte superior de la primera, en lugar de reemplazarlo.   Plotting 0 puts a horizontal line on the graph. Trazado 0 pone una línea horizontal en el gráfico.   Intersections of the sine wave with this line represent solutions of the first equation. Las intersecciones de la onda sinusoidal con esta línea representan las soluciones de la primera ecuación.   Approximate values can be obtained in the Figure window by clicking on Tools / Zoom In, clicking on a desired intersection to enlarge that area of the graph, clicking on Tools / Data Cursor, and then clicking on that intersection again to give the approximate values of x and y there. Los valores aproximados se pueden obtener en la ventana de la figura, haga clic en Herramientas / Zoom In, hacer clic en una intersección deseada para agrandar el área de la gráfica, al hacer clic en Herramientas / cursor de datos, y luego haciendo clic en la intersección de nuevo para dar los valores aproximados de x e y allí.   Try this on the first two intersections to the right of the origin (x > 0). Pruebe esto en los primeros dos cruces a la derecha del origen (x> 0).   Write down your results to compare with those found below. Anote sus resultados para comparar con las que se encuentran a continuación.  
Here are the steps to find a solution numerically: Estos son los pasos para encontrar una solución numérica:
  1. Convert the equation to a function consisting of everything moved to the left-hand side, eg func2(x) = sin(x)-1/2. Convertir la ecuación de una función que consiste en todo lo que mueve a la izquierda, por ejemplo, func2 (x) = sen (x) -1 / 2.
  2. Create this function in the MATLAB editor, save to the Current Directory, and make certain the current directory is in the path (File / Set Path). Crear esta función en el editor de MATLAB, salvo que el directorio actual, y asegurarse de que el directorio actual está en la ruta (Archivo / Set Path).   For example: Por ejemplo:
function out = func2(x) función de func2 = (x)
out = sin(x) - 1/2; a = sin (x) - 1 / 2;
end final
  1. Plot this function over the range of interest to see where the solutions are, eg: Representar esta función en el rango de interés para ver dónde están las soluciones, por ejemplo:
                  >> clear , x = - 4:0.01:4; >> Claro, x = - 4:0.01:4;   plot(x,func2(x)) plot (x, func2 (x))
  1. Use one of the following formats to find the solution: Utilice uno de los siguientes formatos para encontrar la solución:
            >> fzero ('func2',3) >> Fzero ('func2', 3)   or o   >> fzero (@func2,3) >> Fzero (@ func2, 3)   or o   >> fzero ('func2', [2,3]) >> Fzero ('func2', [2,3])
MATLAB finds the value of x nearest 3 that gives func2 = 0. MATLAB obtiene el valor de x más cercano que da 3 func2 = 0.   Notice (“ whos ” or Workspace) that the result is double, so no conversions are necessary for subsequent numeric calculations. Aviso ("whos" o área de trabajo) que el resultado es doble, por lo que no son necesarias conversiones para su posterior cálculo numérico.
Numerical solution of two or more equations in implicit forms (eg, f1( x ,y )=0, f2( x,y )=0) Solución numérica de dos o más ecuaciones en forma implícita (por ejemplo, f1 (x, y) = 0, f2 (x, y) = 0)
 
We use the " fminsearch " command. Usamos el "fminsearch" de comandos.   Consider as an example the following two implicit equations (already in MATLAB format): Tomemos como ejemplo las siguientes dos ecuaciones implícitas (ya en formato de MATLAB):
      0.5 = (200+3*x+4*y )^ 2 / ((20+2*x+3*y)^2 * x) 0.5 = (200 x 3 * 4 * y) ^ 2 / ((20 +2 * x +3 * y) ^ 2 * x)
      10 = (20+2*x+3*y)*y / x 10 = (20 +2 * x +3 * y) * y / x
Use the following steps: Use los siguientes pasos:
  1. Move everything to the left-hand side in all equations. Que todo se mueva a la izquierda en todas las ecuaciones.
  2. Using MATLAB's edit window, create a function that calculates the deviations from 0 when arbitrary values are used for the variables. Usando la ventana de MATLAB editar, crear una función que calcula las desviaciones de 0 cuando se usan valores arbitrarios para las variables.   The final output of the function is the sum of the squares of these deviations. El resultado final de la función es la suma de los cuadrados de estas desviaciones.   Following is the code for our example, and would be saved as meth_reac.m in MATLAB's Current Directory, which must also be in the Path (File/Set Path). Este es el código para nuestro ejemplo, y se guardarán como meth_reac.m en el directorio actual de MATLAB, que también debe estar en la ruta (Archivo / Set Path).
function out= meth_reac (guesses) a cabo la función = meth_reac (conjeturas)
% function to calculate the values of x and y % Función para calcular los valores de x e y
% satisfying the two equibiliubrium relations % Satisfacción de las dos relaciones equibiliubrium
% for a methanol reactor, CO + 2H2 = CH30H % Para un reactor de metanol, CO + 2H2 = CH30H
% CO2 + 3H2 = CH3OH + H2O (coal to chems case study) % CO2 + 3H2 = CH3OH + H2O (carbón de estudio de caso Chems)
% x is the molar flow rate of CO, y of CO2 ( kmol /h) X% es la tasa de flujo molar de CO, y de CO2 (kmol / h)
% After saving: >> fminsearch ( ' meth_reac ',[25,3]); x= ans (1), y= ans (2) Después de guardar%:>> fminsearch ('meth_reac', [25,3]); x = ans (1), y = ans (2)
% Any positive values work as initial guesses in this example % Los valores positivos de trabajo en los supuestos iniciales en este ejemplo
x= guesses ( 1); y= guesses (2); x = conjeturas (1), y = conjeturas (2);
eq1 = 0.5 -(200+3*x+4*y )^ 2/(20+2*x+3*y)^2/x; eq1 = 0,5 - (200 x 3 * 4 * y) ^ 2 / (20 +2 * x +3 * y) ^ 2 / x;
eq2 = 10 -(20+2*x+3*y)*y/x; EQ2 = 10 - (20 x 2 * 3 * y) * y / x;
out= eq1^2+eq2^2; a = eq1 ^ 2 + eq2 ^ 2;
end final
3. 3.       In the Command window, type " fminsearch ( 'function name',[guessed values]). En la ventana de comandos, escriba "fminsearch (" nombre de la función ', [adivinado valores]).   For our example, Para nuestro ejemplo,
                  >> fminsearch ( ' meth_reac ',[25,3]); x= ans (1), y= ans (2) >> Fminsearch ('meth_reac', [25,3]); x = ans (1), y = ans (2)
You can check your result by using the symbolic "solve" command, as follows for our example: Puede comprobar el resultado mediante el uso de lo simbólico "resolver" de comandos, de la siguiente manera para nuestro ejemplo:
>> clear , syms xy >> Claro, syms xy
>> eq1='0.5 =( 200+3*x+4*y)^2/(20+2*x+3*y)^2/x' >> Eq1 = '0 .5 = (200 x 3 * 4 * y) ^ 2 / (20 +2 * x +3 * y) ^ 2 / x '
>> eq2='10 =( 20+2*x+3*y)*y/x' >> Eq2 = '10 = (20 +2 * x +3 * y) * y / x '
>> [ x y]= solve (eq1,eq2,x,y) >> [X y] = solve (EQ1, EQ2, x, y)
Note that several solutions are produced, from which you have to select the physically reasonable one. Tenga en cuenta que varias soluciones que se producen, de la que usted tiene que seleccionar el que físicamente razonable.   If this is the first solution, then to obtain double-precision numerical variables we use: Si esta es la primera solución, luego de obtener las variables de doble precisión numérica que utilizamos:
                  >> x=double(x(1)), y= double( y(1)) >> X = double (x (1)), y = doble (y (1))
(The equations in this example are based on the equilibrium relationships for a chemical reactor making methanol from CO, CO 2 and H 2 as part of an existing plant that produces a variety chemicals starting with the gasification of coal, ie coal reacting with water at high temperature.) (Las ecuaciones de este ejemplo se basan en las relaciones de equilibrio de un reactor químico metanol a partir de la toma de CO, CO 2 y H 2 como parte de una planta existente que produce una variedad de productos químicos a partir de la gasificación del carbón, es decir, que reacciona con el agua en altas temperaturas.)
Numerical solution of simultaneous linear equations using the matrix backslash (\) method Solución numérica de ecuaciones lineales simultáneas utilizando la barra invertida de la matriz (\) método
MATLAB uses Gaussian elimination to solve systems of linear equations via the backslash matrix command (\). MATLAB utiliza la eliminación de Gauss para resolver sistemas de ecuaciones lineales a través del comando de barra invertida de la matriz (\).   As an example, consider the following three equations: Como ejemplo, considere las siguientes tres ecuaciones:
      2x-3y+4z=5 2x-3y 4 z = 5
      y+4z+x=10 y +4 z + x = 10
      -2z+3x+4y=0 -2z 3 x 4 y = 0
The procedure is as follows: El procedimiento es el siguiente:
  1. Each equation must first have each variable in the same order on the left-hand side, with the constants on the right-hand side. Cada ecuación debe tener cada variable en el mismo orden en el lado izquierdo, con las constantes en el lado derecho.   This should be done using pencil and paper. Esto debe hacerse con lápiz y papel.   Students commonly assume they can do this while entering the information in MATLAB, and frequently make mistakes doing so. Los estudiantes generalmente asumen que pueden hacer esto al introducir los datos en MATLAB, y con frecuencia se equivocan al hacerlo.   For our example, we write: Para nuestro ejemplo, escribimos:
2x - 3y + 4z = 5 2x - 3y + 4z = 5
x + y + 4z = 10 x + y + 4z = 10
3x + 4y - 2z = 0 3x + 4y - 2z = 0
  1. In MATLAB, create matrices of coefficients for the variables and constants on the right-hand sides. En MATLAB, crear matrices de coeficientes de las variables y constantes en los laterales de la derecha.   Thus for our example: Así, para nuestro ejemplo:
            >> clear, C = [2,-3 ,4 ; 1,1,4; 3,4,-2], >> Claro, C = [2, 3, 4, 1,1,4, 3,4, -2],   B = [5; 10; 0] B = [5, 10, 0]
  1. Solve for x, y and z using: Resuelva para x, y y z utilizando:
            > > >>   A = C\B, x = A(1), y = A(2), z = A(3) A = C \ B, x = A (1), y = A (2), z = A (3)
      Check your results using: >> C*A - B Compruebe los resultados utilizando:>> C * A - B
      (Note that these are matrix operations; you MUST NOT use a dot (.) before * or \) (Tenga en cuenta que se trata de operaciones con matrices,. Usted no debe usar un punto () antes de * o \)      
Compare this result with that obtained using MATLAB symbolic mathematics for the same system of equations. Comparar este resultado con el obtenido utilizando las matemáticas MATLAB simbólico para el mismo sistema de ecuaciones.
Another application of the backslash matrix operator is to fit data to a non-linear equation. Otra aplicación de la matriz del operador barra invertida es para ajustar los datos a una ecuación no lineal.   We use an example with the following y versus data: Usamos un ejemplo con los siguientes datos y en comparación con:
      >> clear ; t = [0, .3, .8, 1.1, 1.6, 2.3]'; >> Claro, t = [0, 0.3, 0.8, 1.1, 1.6, 2.3] ';   y = [0.5, 0.82, 1.14, 1.25, 1.35, 1.40]'; y = [0,5, 0,82, 1,14, 1,25, 1,35, 1,40];   plot(t , y ,'o ') plot (t, y, 'o')
Notice that this does not give a straight line plot. Tenga en cuenta que esto no da una parcela en línea recta.    Instead we will try a quadratic fit ( without using the Basic Fitting tool on the graph window or the " polyfit " command). En su lugar vamos a tratar de un ajuste de segundo grado (sin utilizar la herramienta de montaje básico en la ventana gráfica o el comando "polyfit").   That is, we want to find the values of the coefficients (a 0 , a 1 , a 2 ) that Es decir, queremos encontrar los valores de los coeficientes (a, 0 a 1, a 2) que best fit these data to the form y = a 0 + a 1 t + a 2 t 2 . mejor se adapten a estos datos a la forma y = a 0 + a 1 t + a t 2 2.   We have 6 values each of t and y, from which we generate 6 equations in the format a 0 + ta 1 + t 2 a 2 = y matching that required for solution of simultaneous linear equations: Contamos con 6 valores de cada uno de tyy, de la que generan el 6 ecuaciones en el formato de un 0 + 1 + ta t 2 a 2 = y juego que se requiere para la solución de ecuaciones lineales simultáneas:
a 0 un 0                            = =   0.5 0.5
a 0 + 0.3a 1 +0.3 2 a 2 a 0 + 0,3 1 0,3 2 a 2   = =   0.82 0.82
a 0 + 0.8a 1 +0.8 2 a 2 a 0 + 0,8 0,8 1 2 a 2   = =   1.14 1.14
a 0 + 1.1a 1 +1.1 2 a 2 a 0 + 1.1 1 1.1 2 a 2    = =   1.25 1.25
a 0 + 1.6a 1 +1.6 2 a 2 a 0 + 1,6 1 1,6 2 a 2    = =   1.35 1.35
a 0 + 2.3a 1 +2.3 2 a 2 a 0 + 2.3 a un 2.3 2 a 2   = =   1.40 1.40
Thus we have six simultaneous equations, but only 3 unknowns. Por lo tanto tenemos seis ecuaciones simultáneas, pero sólo el 3 incógnitas.   We cannot expect to get values for a 0 , a 1 and a 2 that would exactly satisfy all 6 equations. No podemos esperar para obtener los valores de un 0, un 1 y un 2 que satisfagan a todos exactamente seis ecuaciones.   The backslash operator gives the least squares values instead. El operador barra invertida ofrece el menor valor en lugar de cuadrados.   We must put these 6 equations in the form C*A=B, as follows (assuming t and y have already been entered, as above): Tenemos que poner estos seis ecuaciones en la forma C * A = B, como sigue (asumiendo que t e y ya se han introducido, como el anterior):
>> C( :,1) = ones ( length (t),1) >> C (:, 1) = ones (longitud (t), 1)
>> C( :,2)=t >> C (:, 2) = t
>> C( :,3)=t.^2 >> C (:, 3) = t. ^ 2
>> B = y >> B = y
>> A = C\B >> A = C \ B
>> a0 = A(1), a1 = A(2), a2 = A(3) >> A0 = A (1), a1 = A (2), a2 = A (3)
>> tfit = 0:0.1:2.3; yfit = a0 + a1* tfit + a2* tfit .^2; >> = Tfit 0:0.1:2.3; yajustado = a0 + a1 + a2 * tfit tfit * ^ 2.;
>> plot(t , y ,'o ', tfit,yfit ); >> Plot (t, y, 'o', tfit, yajustado);
This is a general method and not confined to fitting data to polynomials. Este es un método general y no se limita a los datos de ajuste de polinomios.   See fitting data to non-polynomial equations . Ver los datos de ajuste de las ecuaciones polinómicas que no .

No hay comentarios:

Publicar un comentario