Monday, May 7, 2012

introducción a Matlab simbólico

>> syms x; definición de variable tipo simbólico
 >> 2*x+3*x suma algebraica
 >> a=[x 5; 3*x 4]; matriz con elementos símbolos
 >> t=inv(a) su inversa también contiene símbolos
 >> t=solve(2*x^2+3*x-2) solución de una ecuación 
 >> f=3*x^2+5*x; definición simbólica de una función 
 >> t=factor(f) factorar la expresión
 >> s=expand(t) expandirla
 >> e=taylor(exp(x)) expansión con la serie de Taylor
 >> limit(sin(x)/x) obtencíon de límites de funciones
 >> syms y;
 >> f=2*x^3+3*y^2 una función de dos variables
 >> g=diff(f,x) derivada parcial
 >> u=int(f,x) integrar en x Funciones adicionales con expresiones simbólicas 
 >> f='2*t+1'; definición de una función en forma literal
 >> t=3;
 >> y=eval(f) evaluación de la función 
>> [a,b] = solve('a^2 + a*b - b = 3','a^2 - 4*b - 5 = 0') resuelve un sistema de dos ecuaciones no lineales >> a=double(a) para expresarlas en forma real
 >> b=double(b)
 >> f='exp(x)-pi*x';
 >> x=solve(f)
 >> x=double(x) cambia la solución simbólica a real x = 0.5538 resultados de MATLAB 1.6385 
 >> x=fzero(f,2) solución de una ecuación con un valor inicial x = 1.6385 resultado de MATLAB 
 >> x=fzero(f,[1,2]) solución usando un rango para la raiz x = 1.6385 resultado de MATLAB
 >> u=diff(f) diferenciación 
 >> v=int(f) integración analítica 
 >> r=int(f, 0, 2) integración entre límites
 >> g='x*exp(-x)';
 >> r=int(g, 0, Inf); integral impropia solución analítica y gráfico de una EDO de primer orden con una condición en el inicio 
 >> y=dsolve('Dy=(x-y)/x','y(0)=0','x')
 >> ezplot(y,0,2);
 >> grid on EDO de segundo orden con condiciones en el inicio y gráfico de la solución
 >> y=dsolve('D2y+Dy+2*y-x-3=0','y(0)=0,Dy(0)=1','x')
 >> ezplot(y,0,2);
 >> grid on; EDO de segundo orden con condiciones en los bordes
 >> y=dsolve('D2y-Dy+2*y-5*x-3=0','y(0)=0,y(1)=2','x')
 >> ezplot(y,0,2);
 >> grid on
 >> f=’2*sin(x)*exp(x)’;
 >> [x,y]=fminbnd(f,-2,2) encuentra un mínimo local de f en 1 £ x £ 4
 >> ezplot(f,-2,2)

Monday, April 23, 2012

Simulaciòn de un sistema modelado con el método de armónicos Introducción El dominio armónico (HD) es un marco de referencia para el análisis de sistemas de potencia en estado estable, el cual es capaz de modelar el acoplamiento entre fases y entre armónicos y procesa simultáneamente la presencia de fuentes de voltajes y corrientes de diferentes frecuencias . El modelado en el HD es acompañado por métodos de solución iterativos tipo Gauss-Seidel o Newton-Raphson, donde el dispositivo no lineal es remplazado en cada iteración por un equivalente de Norton, y es resuelto con el resto del sistema. TAREA A REALIZAR La tarea fundamentar es simular el sistema dado y luego modelarlo en dominio armónico y comparar los resultado en ambas simulaciones El sistema a simular es el siguiente [■((i_a ) ̅@(i_b ) ̅@i ̅_c )] =-[■(R/L&0&0@0&R/L&0@0&0&R/L)][■(i_a@i_b@i_c )]+1/L [■(V_a@V_b@V_c )] Donde Va=sin(t) Vb=sin(t-2π/3) Vc=sin(t-4π/3) El sistema se puede representar en la siguiente forma (di_a)/dt=(-R)/L i_a+V_a/L (di_b)/dt=(-R)/L i_b+V_b/L (di_c)/dt=(-R)/L i_c+V_c/L En modelo armónico el sistema puede representarse como (dI_a)/dt=-(R/L 〖+D)I〗_a+(V_a h)/L (dI_b)/dt=-(R/L 〖+D)I〗_b+(V_b h)/L (dI_c)/dt=-(R/L 〖+D)I〗_c+Vch/L SIMULACIONES Y RESULTADOS Primero se simuló el sistema original Aquí esta el código en matlab La función tarea3.m donde están descrito las ecuaciones function [dx] = tarea3(t,x) %clc las ecuaciones del sistema original global R L Va Vb Vc %FunctionOne = b*x(1)+0.5*(a-b)*(abs(x(1)+1)-abs(x(1)-1)); %dx(1) = x(1).*(1-x(1)-a.*x(2)); %dx(2) = b.*x(1).*(x(1)-x(2)); L=0.1; R=0.01; Va = sin(t) ; Vb = sin(t-120) ; Vc = sin(t-240) ; dx(1) = (R/L).*x(1)+ (1/L)*Va ; dx(2) = (R/L).*(x(2))+ 1/L*Vb ; dx(3) = (R/L).*(x(3))+ 1/L*Vc ; dx = dx' ; end La función tarea3._metodo m para resolver las ecuaciones de tarea3.m utilizando runge kutta de orden 4 close all clear clc global R L %para cambiar el punto de operacion cambia las siguientes variables R=0.01; L=0.1; X0=[0 0 0]; T=[0 100]; [t x]=ode45(@tarea3,T,X0); plot(t,x) La grafica de simulacion del sistema sin modelo armonico SIMULACION CON MODELO ARMONICO La función tarea32.m donde están descrito las ecuaciones function [dx] = tarea32(t,x) %clc para modelo harmonico global R L Vah Vbh Vch %FunctionOne = b*x(1)+0.5*(a-b)*(abs(x(1)+1)-abs(x(1)-1)); %dx(1) = x(1).*(1-x(1)-a.*x(2)); %dx(2) = b.*x(1).*(x(1)-x(2)); L=0.1; R=0.01; Vah = sin(t) ; Vbh = sin(t-120) ; Vch = sin(t-240) ; dx(1) = ((R/L).*x(1)+ (1/L)*Vah)/2 ; dx(2) = ((R/L).*(x(2))+ 1/L*Vbh)/2 ; dx(3) = ((R/L).*(x(3))+ 1/L*Vch)/2 ; dx = dx' ; end La función tarea32._metodo m para resolver las ecuaciones de tarea3.m utilizando runge kutta de orden 4 close all clear clc global R L %para cambiar el punto de operacion cambia las siguientes variables R=0.01; L=0.1; X0=[0 0 0]; T=[0 100]; [t x]=ode45(@tarea32,T,X0); plot(t,x) La grafica de la simulación del sistema modelado en armónicos Concllusion Los dos sistemas se comportan de manera similar esto es una prueba de que a modelar un sistema en modelo armonico el sistema no pierde su dinámica pero si se simplifica su análisis.

Using Matlab to draw phase portraits


This is a quick notes to help you
draw phase portraits using the quiver command in Matlab. It is best to draw
the phase portrait in small pieces. The system we shall consider is


[x1, x2] = meshgrid(-.5:0.05:0.5, -.5:.05:.5);
x1dot = -x1 - 2 *x2 .*x1.^2+x2; %Note the use of .* and .^
x2dot = -x1-x2;
quiver(x1,x2,x1dot, x2dot)

Monday, March 5, 2012

Una interface gráfica para estudiar las trayectorias en plano de fase de dos estados.


function dfase(op)

% DFASE(OP) Es una interface gráfica para estudiar las trayectorias en plano de fase
% de dos estados.
%
% Tiene la posibilidad de graficar:
%   => Las trayectoria de los estados ingresando la condición inicial con la
%   posición del mouse cuando se hace un click.
%   => Las isoclinas.
%   => Los vectores que indican la pendiente.
%
% Haciendo un click con el mouse en el plano de fase, se cálculan y grafican las
% trayectorias que describen los estados.
% El método de resolución está basado en el método de Runge-Kutta, consultar
% help de ODE45 para mayores destalles. Las ecuaciones pueden ser lineales o no.
% Como tiene una tolerancia fijada de antemano puede que algunas ecuaciones no lineales
% muy complicadas fallen en la convergencia. En la mayoría de los casos no presentan
% problemas.
%
% Para utilizarla simplemente ingrese "dfase3" desde el Command Window
%
%


% si no se ingresa opción entonces se define la GUI
if nargin<1
   op=1;
end,


if op==1
   % dibujo toda la GUI
 
   % para evitar problemas de localización de objetos
   h=findobj('Tag','FigFase');
if ~isempty(h)
  errordlg('Ya existe una ventana Diagrama de Fase',...
     'Error en Diagrama de Fase',...
     'modal');
  return,
end,

 
   Hf = figure('Units','normalized',...
    'Position',[0.1 0.1 0.8 0.8],...
  'NumberTitle','off',...
  'Name','Diagrama de Fase',...
      'Menubar','none',...
      'Tag','FigFase');
 
   c=get(gcf,'Color');
 
% plano de fase
Ha1=axes('Units','normalized',...
  'Position',[0.04 0.25 0.6 0.69],...
  'FontSize',8,...
  'Xlim',[-10 10],...
      'Ylim',[-10 10],...
      'box','on',...
  'Tag','fase',... % el tag es "fase"
  'NextPlot','add',...
  'ButtonDownFcn','dfase(3)');

title('Diagrama de fase');
 
   % gráfico de la velocidad (x2)
Ha2=axes('Units','normalized',...
'Position',[ 0.68 0.25 0.3 0.3 ],...
      'FontSize',8,...
      'box',' on',...
  'NextPlot','add',...
    'Tag','velocidad'); % el tag es "velocidad"

title('Velocidad (x2)');

% gráfico de la posición (x1)
Ha3=axes('Units','normalized',...
  'Position',[ 0.68 0.64 0.3 0.3 ],...
      'box',' on',...
  'FontSize',8,...
  'NextPlot','add',...
  'Tag','posicion');

title('Posición (x1)');
 
   % segunda ecuación
uicontrol('Style','text',...
      'Units','normalized',...
      'BackgroundColor',c,...
      'ForegroundColor',[1 1 1],...
  'Position',[ 0.05 0.15 0.2 0.03 ],...
  'HorizontalAlignment','left',...
  'String','Primer ecuación:')

uicontrol('Style','edit',...
  'Units','normalized',...
  'BackgroundColor',[1 1 1],...
  'Position',[ 0.25 0.14 0.2 0.05 ],...
  'HorizontalAlignment','left',...
    'String','x2',...
  'Tag','PrimerEc')

   % segunda ecuación
uicontrol('Style','text',...
  'Units','normalized',...
      'BackgroundColor',c,...
      'ForegroundColor',[1 1 1],...
  'Position',[ 0.05 0.08 0.2 0.03 ],...
  'HorizontalAlignment','left',...
  'String','Segunda ecuación:')
 
uicontrol('Style','edit',...
  'Units','normalized',...
  'BackgroundColor',[1 1 1],...
  'Position',[ 0.25 0.07 0.2 0.05 ],...
    'HorizontalAlignment','left',...
  'String','-x1-x2',...
  'Tag','SegundaEc');

% boton vectores
uicontrol('Style','push',...
  'Units','normalized',...
  'Position',[ 0.5 0.14 0.12 0.05 ],...
  'String','Vectores',...
  'Tag','Push1',...
  'Callback','dfase(2)');

% boton isoclinas
uicontrol('Style','push',...
  'Units','normalized',...
  'Position',[ 0.5 0.07 0.12 0.05 ],...
  'String','Isoclinas',...
  'Tag','Push2',...
  'Callback','dfase(5)');
 
% boton borrar
uicontrol('Style','push',...
  'Units','normalized',...
  'Position',[ 0.65 0.07 0.12 0.05 ],...
  'String','Borrar',...
  'Tag','Push3',...
  'Callback','dfase(4)');
 
   % boton imprimir
uicontrol('Style','push',...
  'Units','normalized',...
  'Position',[ 0.65 0.14 0.12 0.05 ],...
  'String','Imprimir',...
  'Tag','Push4',...
  'Callback','print');

   % boton cerrar
uicontrol('Style','push',...
  'Units','normalized',...
  'Position',[ 0.8 0.07 0.12 0.05 ],...
  'String','Cerrar',...
  'Tag','Push5',...
  'Callback','close(gcf)');

% grafico dos líneas que pasan por el origen
set(Hf,'CurrentAxes',Ha1);
plot([-10 0;10 0],[0 -10;0 10],...
  'Color',[1 1 1],...
  'LineWidth',0.1);

elseif op==2
   % Para graficar los vectores
 
   % obtengo las ecuaciones
   ec1=get(findobj('Tag','PrimerEc'),'String');
   ec2=get(findobj('Tag','SegundaEc'),'String');
 
   % planteo la ecuación de la pendiente
   ec=['m=(' ec2 ')./(' ec1 ');'];

   % hago al axes del plano de fase el actual
   Ha=findobj('Tag','fase');
   set(gcf,'CurrentAxes',Ha);
 
% grafico los vectores
for j=1:20
      for s=1:20
         % calculo la pendiente y para un dado punto del plano
         a=1.5;b=0.75;
         x1=-10+j*a;
     x2=-10+s*a;
         eval(ec);
         % calculo el punto final de modo que tenga una longitud fija
         xd=sqrt((b^2)/(1+m^2));
      x21=m*xd+x2;
      x11=x1+xd;
  plot([x1 x11],[x2 x21],'y')
end,
end,
 
 
elseif op==3
   % Para calcular y graficar las trayectorias de los estados
   % utilizo ODE45 (Runge-Kuta)
 
   % primero necesito armar un archivo .m con las ecuaciones diferenciales
   f=fopen('ectmp.m','wt+');
 
   fprintf(f,'%s','function yd=ecuacion(t,x)');
   fprintf(f,'\n\n\n\n');
 
   % acomodo las ecuaciones ingresadas
   ec1=get(findobj('Tag','PrimerEc'),'String');
   ec2=get(findobj('Tag','SegundaEc'),'String');
 
   % necesito exprezarlas como un vector para la ODE45
   ec11=strrep(ec1,'x1','x(1)');
   ec22=strrep(ec2,'x1','x(1)');
   ec11=strrep(ec11,'x2','x(2)');
   ec22=strrep(ec22,'x2','x(2)');

   ec=['yd=[' ec11 ';' ec22 '];'];
 
   fprintf(f,'%s\n',ec);
 
   fclose(f);
 
   % capturo las condiciones iniciales desde la posición actual del mouse
   yo=get(findobj('Tag','fase'),'CurrentPoint');
 
   % resuelvo las ecuaciones diferenciales
   [t,y]=ode45('ectmp',0,10,yo(2,1:2)');
 
   % elimino la función que tiene las ecuaciones de la memoria
   % para que los cálculos sean actuales
   clear ectmp
 
   % grafico
   set(gcf,'CurrentAxes',findobj('Tag','velocidad'));
   hl = findobj('Parent',gca,'Type','line');
   delete(hl);
   plot(t,y(:,1),'w');
 
   set(gcf,'CurrentAxes',findobj('Tag','posicion'));
   hl = findobj('Parent',gca,'Type','line');
   delete(hl);
   plot(t,y(:,2),'w');
 
   set(gcf,'CurrentAxes',findobj('Tag','fase'));
   plot(y(:,1),y(:,2),'w');
 
 
elseif op==4
   % Para borrar los vectores, isoclinas y trayectorias de estados
 
   % hago al axes del plano de fase el actual
   Ha=findobj('Tag','fase');
   set(gcf,'CurrentAxes',Ha);
 
   % busco y borro los objetos tipo líneas
   Hdel=findobj('Parent',Ha,'Type','line');
   delete(Hdel);
 
   % redibujo las líneas que pasan por el origen
   plot([-10 0;10 0],[0 -10;0 10],...
    'Color',[1 1 1],...
  'LineWidth',0.1);


elseif op==5
   % Para calcular y graficar las isoclinas
 
% obtengo las ecuaciones que se ingresaron en forma de cadena  
   ec1=get(findobj('Tag','PrimerEc'),'String');
   ec2=get(findobj('Tag','SegundaEc'),'String');
 
   % trabajo las ecuaciones para trabajar punto a punto
   ec=['m=(' ec2 ')/(' ec1 ')'];
   ec1=strrep(ec,'*','.*');
   ec1=strrep(ec1,'/','./');
   ec1=strrep(ec1,'^','.^');
 
   % calculo 20 valores de pendientes de manera que queden distribuidos
   % en el palno de fase
   x1=[-10*ones(1,5) -10 -6 -2 2 6 10*ones(1,5) 10 6 2 -2 -6];
   x2=[-10 -6 -2 2 6 10*ones(1,5) 10 6 2 -2 -6 -10*ones(1,5)];
   eval([ec1 ';']);
   M=m;
 
   % resuelvo la ecuación para poner en forma explícita x2
   % SE NECESITA SYMBOLIC TOOLBOX
   ecs=solve(ec,'x2');
ecs1=ecs(1,:);
   ecs1=strrep(ecs1,'*','.*');
   ecs1=strrep(ecs1,'/','./');
   ecs1=strrep(ecs1,'^','.^');
 
   % calculo numericamente las isoclinas
x1=-10:0.2:10;
for j=1:20;
      m=M(j);
eval(['x2=' ecs1 ';']);
plot(x1,x2,...
    'Color',[0.8 0.8 0.8])
end,
 
 
end
 

Saturday, February 25, 2012

código en matlab para la simulación de oscilador de chua



% la primera parte son las ecuaciones de modelo
function dx=chua(t,x)
global alfa beta gamma a b
fx1=b.*x(1)+0.5*(a-b).*(abs(x(1)+1)-abs(x(1)-1));
dx(1)=alfa.*(x(2)-x(1)-fx1);
dx(2)=x(1)-x(2)+x(3);
dx(3)=-beta.*x(2)-gamma.*x(3);
dx=dx';
end
% guarde en una carpeta la primera parte del codigo te va a salir como chua.m
%abra otro nuevo script y copiar y pegar esto y estas listo

close all
clear
clc
global alfa beta gamma a b
%para cambiar el punto de operacion cambia las siguientes variables
alfa=10.61;
beta=17.719;
gamma=0.13699;
a=-1.40726;
b=-0.816308;
X0=[10 0 0];
T=[0 500];
[t x]=ode45(@chua,T,X0);
figure
plot(x(:,1),x(:,2))
figure
plot(x(:,2),x(:,3))
figure
plot(x(:,2),x(:,3))
figure
plot3(x(:,1),x(:,2),x(:,3))

Thursday, February 16, 2012

How Vehicle Automation Will Cut Fuel Consumption


   Cars that park themselves and automatically convoy with other cars could reduce congestion and emissions.
Several automakers are developing technology to let cars drive themselves, mainly as a way to make driving more convenient and improve safety. But it could also significantly reduce gasoline consumption, says Nady Boules, the director of GM's Electrical and Controls Integration Lab.
Increased automation could reduce congestion, but also allow for radical redesigns of automobiles to make them lighter and more fuel-efficient. Boules says partially automated vehicles that let drivers take their hands off the steering wheel and the accelerator, but still require them to pay attention, could be sold by the end of the decade.
Some cars already have a system that prompts drivers to change the way they accelerate to drive more efficiently. Allowing the car to control acceleration automatically could also save fuel.
But the biggest effects could come with full automation. Cars that park themselves—a trick GM has demonstrated with its EN-V concept vehicle—could save fuel by eliminating the need for drivers to circle the block waiting for a parking space to open up. The ambition is for a car to drop its owner off and go directly to the nearest available parking spot—even if that spot happens to be miles away, too far for the owner to walk. When it's time to leave, the owner notifies the car with a smart phone, and it picks him or 

Vehicle-to-vehicle communication, which allows vehicles to travel on highways very close together at consistent speeds, could also reduce fuel consumption. If a truck in a convoy brakes, it sends a signal slowing down the following trucks instantaneously. A spacing of four meters reduces wind resistance for the following trucks, and could reduce fuel consumption by 10 to 15 percent, Boules says. Vehicle-to-vehicle communication could also reduce congestion by cutting accidents, coordinating traffic intelligently, and "getting rid of those drivers who accelerate through red lights." The U.S. Department of Transportation is sponsoring work to enable this last goal using sensors in stop lights that can communicate with smart vehicles.
In the more distant future, if automated cars prove as safe as Boules thinks they can be, it could allow engineers to completely redesign cars. "You could remove the weight dedicated to crash protection, using very light materials for the skin instead of metals," Boules says.
Boules believes fully automated cars could be built by the next decade, but admits that new regulations will be needed before they can be sold.
Automakers have been working on vehicle automation for decades, but the work recently got a boost from a DARPA-sponsored contest to develop vehicles that can navigate a simulated urban environment on their own. A team that included GM and Carnegie Mellon University won that contest. Google is also pushingvehicle automation, and has tested autonomous vehicles for over a hundred thousand miles; the company is also reportedly sponsoring a bill that clears the way for automated vehicles to drive on public roads in Nevada. 


Tuesday, February 14, 2012

Automation Engineer Job Description

Automation engineers work with mechanical processes and equipment that perform programed tasks in sectors such as manufacturing or food processing. This includes maintaining robotics that manufacture cars or produce pharmaceuticals.
  1. Duties

    • An automation engineer will design, implement and test automated machines. Automation engineers troubleshoot problems with mechanical equipment and ensure it is functioning properly. Automation engineers also design entire systems, consisting of several machines, which are designed to perform a specific function.

    Education

    • Automation engineers hold a four-year Bachelor of Science degree in Automation, Mechanical, Electrical or Computer Engineering. A master's degree may be required for some positions.

    Skills

    • To be successful as an automation engineer, one must have excellent communication and problem-solving skills. An understanding of computer programming and software development is required as well.

    Salary

    • The average salary for an automation engineer is $82,000.

    Job Outlook

    • Manufacturers continue to implement automated processes, resulting in a continued demand for automation enginineers