You are on page 1of 6

# 1. Linear system of equations.

## Solve the following system of equations

using \. Compute and display the error vector

3a + 6b + 4c = 1

a + 5b = 2

7b + 7c = 3
% hacer la matriz
mat=[3 6 4;1 5 0;0 7 7];
y=[1;2;3];
abc=mat\y;
abc=mat\y
% Compruebe que la solución es correcta, si es así, esto debería estar
cerca de 0
errorVector=mat*abc-y

mat =

3 6 4

1 5 0

0 7 7

y=

abc =

-0.5824

0.5165

-0.0879

errorVector =

1.0e-15 *

0.2220

0.4441
𝟓
2. Numerical integration. What is the value of: ∫𝟎 𝒙𝒆−𝒙/𝟑 𝒅𝒙 ? Use trapz or
quad. Compute and 0 display the difference between your numerical answer
and the analytical answer: −24 𝒆−𝟓/𝟑 + 9
% hacer el vector x
x=linspace(0,5,1000);
approximate=trapz(x,x.*exp(-x/3));
actual=-24*exp(-5/3)+9;
disp(['Difference between approximate and actual integral is ' ...
num2str(abs(approximate-actual))]);

## Difference between approximate and actual integral is 2.3504e-06

𝟏 𝟐
3. Computing the inverse. Calculate the inverse of and verify that
𝟑 𝟒
when you multiply the original matrix by the inverse, you get the identity
matrix (inv). Display the inverse matrix as well as the result of the
multiplication of the original matrix by its inverse.
temp=[1 2;3 4];
i=inv(temp)
identity=i*temp
i=

-2.0000 1.0000

1.5000 -0.5000

identity =

1.0000 0

0.0000 1.0000
4. Fitting polynomials. Write a script to load the data file randomData.mat
(which contains variables x and y) and fit first, second, third, fourth,
and fifth degree polynomials to it. Plot the data as blue dots on a figure,
and plot all five polynomial fits using lines of different colors on the
same axes. Label the figure appropriately. To get good fits, you’ll have to
use the centering and scaling version of polyfit (the one that returns
three arguments, see help) and its counterpart in polyval (the one that
accepts the centering and scaling parameters). It should
% polynomialFitting
% Cargar los datos
load randomData
% Hacer una figura y trazar los datos
figure
plot(x,y,'k.','markersize',15);
hold on
% polinomios de diversos grados y trazarlos sobre la figura
degree=1:5;
colors=jet(5);
for n=1:length(degree)
% Ajustar los datos, el centrado y su reducción
[P,S,MU]=polyfit(x,y,degree(n));
% representar los datos
plot(x,polyval(P,x,S,MU),'color',colors(n,:),'linewidth',2);
end
% añadir etiquetas
xlabel('X'); ylabel('Y');
title('Polynomial fits to noisy data');
legend('Data','Order 1','Order 2','Order 3','Order 4','Order 5');
5. Hodgkin-Huxley model of the neuron. You will write an ODE file to
describe the spiking of a neuron, based on the equations developed by
Hodgkin and Huxley in 1952 (they received a Nobel Prize for this work). The
main idea behind the model is that ion channels in the neuron’s membrane
have voltage-sensitive gates that open or close as the transmembrane
voltage changes. Once the gates are open, charged ions can flow through
them, affecting the transmembrane voltage. The equations are nonlinear and
coupled, so they must be solved numerically.
% dydt=HHODE(t,y)
% Archivo para las ecuaciones Hodgkin-Huxley. El vector de entrada Y
contiene Las variables de estado n, m, H, V en ese orden
function dydt=HHODE(t,y)
% Definir las constantes
C=1; gK=36;
gNa=120;
gL=0.3;
EK=-72;
ENa=55;
EL=-49.4;
% extraer los valores actuales de las variables
n=y(1);
m=y(2);
h=y(3);
V=y(4);
% evaluar las derivadas
dndt=(1-n)*alphan(V)-n*betan(V);
dmdt=(1-m)*alpham(V)-m*betam(V);
dhdt=(1-h)*alphah(V)-h*betah(V);
dVdt=-1/C*(gK*n^4*(V-EK)+gNa*m^3*h*(V-ENa)+gL*(V-EL));
% Ponga los derivados en un vector columna
dydt=[dndt;dmdt;dhdt;dVdt];

## A continuación se muestra la secuencia de comandos que resuelve las ecuaciones

diferenciales en HHODE

## % Resuelve las ecuaciones de Hodgkin Huxley en HHODE

% Ejecutar la simulación para obtener valores de estado estacionario
[t,y]=ode45('HHODE',[0 20],[.5 .5 .5 -60]); ySS=y(end,:);

figure
plot(t,y(:,end),'k','linewidth',1.5);
xlabel('Time (ms)');
ylabel('Transmembrane Voltage (mV)');
title('Approaching Steady State');
% Plegar la tensión inicial para encontrar el umbral
figure
for n=1:10
% Ejecutar la simulación, cada vez que incrementar el voltaje
inicial por n mV
[t,y]=ode45('HHODE',[0 20],ySS+[0 0 0 n]);
v=y(:,end);
if max(v)>0
% Si el pico V> 0,la trama con la línea roja
plot(t,v,'r','linewidth',1.5);
else % Si no superó el umbral,la trama con la línea de negro
plot(t,v,'k','linewidth',1.5);
end
hold on;
end
xlabel('Time (ms)');
ylabel('Transmembrane Voltage (mV)');
title('Threshold Behavior');

6. Optional, but highly recommended: Julia Sets. In this problem you will
generate quadratic Julia Sets. The following description is adapted from
Wikipedia at http://en.wikipedia.org/wiki/Julia. For more information about
Julia Sets please read the entire article there.

a. It has been shown that if the modulus of zn becomes larger than 2 for
some n then it is guaranteed that the orbit will tend to infinity. The
value of n for which this becomes true is called the ‘escape velocity’ of a
particular z0 . Write a function that returns the escape velocity of a
given z0 and c . The function declaration should be:
n=escapeVelocity(z0,c,N) where N is the maximum allowed escape velocity
(basically, if the modulus of zn does not exceed 2 for n<N, return N as the
escape velocity. This will prevent infinite loops). Use abs to calculate
the modulus of a complex number
% N = escapeVelocity (z0, c, N)
% Calcula la velocidad de escape de un conjunto de Julia con los
parámetros z0 y c. N Es el número máximo de iteraciones permitidas (si
abs (Z_n) no superan 2 para n <N, N se devuelve.

function n=escapeVelocity(z0,c,N)
n=0; % Inicializar contador
z=z0; % Inicializar Z_n
% Iterar el bucle hasta llegar a N o abs (z)> 2
while abs(z)<=2 && n<N
% Calcular la próxima z
z=z^2+c;
% incrementar contador
n=n+1;
end

## b. To generate the filled in Julia Set, write the following function

M=julia(zMax,c,N). zMax will be the maximum of the imaginary and complex
parts of the various z0 ’s for which we will compute escape velocities. c
and N are the same as defined above, and M is the matrix that contains the
escape velocity of various z0 ‘s.
% M = Julia (Zmax, c, N)
function M=julia(zMax,c,N)
% hacer la red compleja
temp=linspace(-zMax,zMax,500);
[R,I]=meshgrid(temp,temp); Z=R+1i*I;
% Inicializar un M vacio
M=zeros(size(Z));
% Recorrer todos los Z y calcular la velocidad de escape
for row=1:size(Z,1)
for col=1:size(Z,2)
% extraer la z actual
z0=Z(row,col);
% calcular La velocidad de escape
velocity=escapeVelocity(z0,c,N);
% velocidad de escape en M
M(row,col)=velocity;
end
end
% runJulia
% Ejecuta el conjunto de Julia con un valor de z0 agradable
% graficar la figura
M=julia(1, -.297491+i*0.641051,100);
figure;
x=linspace(-.35,.35,500);
imagesc(x,x,atan(.1*M)); axis xy
xlabel('Re(z)');
ylabel('Im(z)');
% hacer zoom
M=julia(.35, -.297491+i*0.641051,250);
figure;
x=linspace(-.35,.35,500);
imagesc(x,x,atan(.1*M)); axis xy
xlabel('Re(z)');
ylabel('Im(z)')