Homework 4...

Fazer download em docx, pdf ou txt
Fazer download em docx, pdf ou txt
Você está na página 1de 8

1. Random variables.

Make a vector of 500 random numbers from a Normal distribution with


mean 2 and standard deviation 5 (randn). After you generate the vector, verify that the sample
mean and standard deviation of the vector are close to 2 and 5 respectively (mean, std).
r=randn(500,1)*5+2;
disp(['Mean: ' num2str(mean(r))]);
disp(['Standard Deviation: ' num2str(std(r))]);
Mean: 2.1422

Standard Deviation: 4.8554

Mean: 2.2406

Standard Deviation: 5.1981

Mean: 2.2553

Standard Deviation: 4.8566

Mean: 2.018

Standard Deviation: 5.0962

Mean: 2.0985

Standard Deviation: 4.9167

2. Flipping a coin. Write a script called coinTest.m to simulate sequentially flipping a coin 5000
times. Keep track of every time you get ‘heads’ and plot the running estimate of the
probability of getting ‘heads’ with this coin. Plot this running estimate along with a horizontal
line at the expected value of 0.5, as below. This is most easily done without a loop (useful
functions: rand, round, cumsum).
% coinTest
% Generar 1000 números aleatorios
r=rand(5000,1);
r=round(r);
count=1:length(r);
headProb=cumsum(r)./count';
% Traza la probabilidad de cabezas
figure
plot(count,headProb,'k','linewidth',1.5);
hold on
plot([1 length(r)],[.5 .5],'r--');
title('Sample Probability of Heads in n flips of a simulated coin');
xlabel('Number of coin flips');
ylabel('Probability of heads');
legend('Sample Probability','Fair coin');
3. Histogram. Generate 1000 Poisson distributed random numbers with parameter

λ= 5 (poissrnd). Get the histogram of the data and normalize the counts so that the histogram
sums to 1 (hist – the version that returns 2 outputs N and X, sum). Plot the normalized
histogram (which is now a probability mass function) as a bar graph (bar). Hold on and also
plot the actual Poisson probability mass function with λ = 5 as a line (poisspdf). You can try
doing this with more than 1000 samples from the Poisson distribution to get better agreement
between the two.
% plotPoisson
% Realiza un histograma de variables aleatorias de poisson y
distribución en la parte superior
r=poissrnd(5,1000,1);
% Hacer el histograma
[n,x]=hist(r,0:max(r));
n=n/sum(n);
% grafique el histograma
figure
bar(x,n,'b');
hold on
plot(x,poisspdf(x,5),'r','linewidth',1.5);
xlabel('Value');
ylabel('Probability');
title('Poisson distribution and observed histogram');
legend('Experimental histogram','Actual Poisson Distribution');
4. Practice with cells. Usually, cells are most useful for storing strings, because the length of
each string can be unique.
% cellProblem
% Inicializar la celda
c=cell(3,3);
% Añadir elementos
c{1,1}='Joe';
c{2,1}='Sarah';
c{3,1}='Pat';
c{1,2}='Smith';
c{2,2}='Brown';
c{3,2}='Jackson';
c{1,3}=30000;
c{2,3}=150000;
c{3,3}=120000;
% Mostrar la celda
disp(c)
% Parte b
c{2,2}='Meyers';
disp(c)
% part c
c{3,3}=c{3,3}+50000;
disp(c)

'Joe' 'Smith' [ 30000]

'Sarah' 'Brown' [150000]

'Pat' 'Jackson' [120000]

'Joe' 'Smith' [ 30000]

'Sarah' 'Meyers' [150000]

'Pat' 'Jackson' [120000]

'Joe' 'Smith' [ 30000]

'Sarah' 'Meyers' [150000]

'Pat' 'Jackson' [170000]


5. Using Structs. Structs are useful in many situations when dealing with diverse data. For
example, get the contents of your current directory by typing a=dir;
% displayDir
% Muestra una lista de los archivos del directorio y el tamaño de Cada
archivo
function displayDir
% Obtener información del directorio actual
a=dir;
% mostrar nombres de los archivos y tamaños
for n=1:length(a)
if ~a(n).isdir
disp(['File ' a(n).name ' contains ' num2str(a(n).bytes) '
bytes.']);
end
end

File HHODE.m contains 1700 bytes.


File Untitled1.m contains 113 bytes.
File Untitled2.m contains 468 bytes.
File Untitled3.m contains 484 bytes.
File Untitled4.m contains 367 bytes.
File displayDir.m contains 377 bytes.
File ejer1.m contains 321 bytes.
File ejer2.m contains 297 bytes.
File ejer3.m contains 76 bytes.
File escapeVelocity.m contains 502 bytes.
File julia.m contains 1015 bytes.
File randomData.m contains 737 bytes.

6. Handles. We’ll use handles to set various properties of a figure in order to make it look like
this:
% handlesPractice
% Representa la función
x=linspace(0,2*pi,100);
y=sin(x);
figure;
plot(x,y,'r');
xlim([0 2*pi]);

set(gca,'xtick',[0 pi 2*pi],'xticklabel',{'0','1','2'});
set(gca,'ytick',[-1:.5:1]);
grid on;
set(gca,'ycolor','g')
set(gca,'xcolor','c');
set(gca,'color','k');
set(gcf,'color',[.3 .3 .3]);
% Agregar las etiquetas
title('One sine wave from 0 to
2\pi','fontsize',14,'fontweight','bold','color','w')
xlabel('X values (in terms of \pi)','fontsize',12,'color','c');
ylabel('Sin(X)','fontsize',12,'color','g');
7. Image processing. Write a function to display a color image, as well as its red, green, and
blue layers separately. The function declaration should be im=displayRGB(filename).
filename should be the name of the image (make the function work for *.jpg images only). im
should be the final image returned as a matrix. To test the function, you should put a jpg file
into the same directory as the function and run it with the filename (include the extension, for
example im=displayRGB(‘testImage.jpg’)). You can use any picture you like, from your files or
off the internet. Useful functions: imread, meshgrid, interp2, uint8, image, axis equal, axis
tight.

En este ejercicio se utilizara como imagen la cúpula del MIT, imagen que se nos muestra en
hw4
% im=displayRGB(filename)
function im=displayRGB(filename)
im0=imread(filename);
M=size(im0,1);
N=size(im0,2);
x0=1:N;
y0=1:M;
[X0,Y0]=meshgrid(x0,y0);
% hacer mallas
if M>=N
x1=linspace(1,N,round(800*N/M));
y1=linspace(1,M,800);
else
x1=linspace(1,N,800);
y1=linspace(1,M,round(800*M/N));
end
% Hacer la nueva malla
[X1,Y1]=meshgrid(x1,y1);
im1=zeros(length(y1),length(x1),3);
for n=1:3
im1(:,:,n)=interp2(X0,Y0,im0(:,:,n),X1,Y1,'cubic');
end
im=zeros(2*size(im1,1),2*size(im1,2),3);
im(1:size(im1,1),1:size(im1,2),:)=im1;
im(1:size(im1,1),size(im1,2)+1:end,1)=im1(:,:,1);
im(size(im1,1)+1:end,1:size(im1,2),2)=im1(:,:,2);
im(size(im1,1)+1:end,size(im1,2)+1:end,3)=im1(:,:,3);
im=uint8(im);
% Muestra la imagen
figure
image(im)
axis equal
axis tight
8. Animation: Brownian motion. Write a function with the following declaration: brown2D(N).
The function takes in a single input N, which is an integer specifying the number of points in
the simulation. All the points should initially start at the origin (0,0). Plot all the points on a
figure using ‘.’ markers, and set the axis to be square and have limits from -1 to 1 in both the x
and y direction. To simulate Brownian motion of the points, write a 1000-iteration loop which
will calculate a new x and y position for each point and will display these new positions as an
animation. The new position of each point is obtained by adding a normally distributed
random variable with a standard deviation of 0.005 to each x and y value (use randn; if you
have 100 points, you need to add 100 distinct random values to the x values and 100 distinct
random values to the y values). Each time that the new positions of all the points are
calculated, plot them on the figure and pause for 0.01 seconds (it’s best to use set and the line
object handle in order to update the xdata and ydata properties of the points, as mentioned in
lecture).
% Simula el movimiento browniano de N puntos.
function brown2D(N)
% Hacer la figura
figure;
axis square
axis([-1 1 -1 1]);
% Hacer las posiciones x e y
x=zeros(N,1);
y=zeros(N,1);
h=plot(x,y,'.k');
for n=1:1000
% Actualizar las posiciones en x e y
x=x+randn(size(x))*.005;
y=y+randn(size(y))*.005;
% graficar
set(h,'xdata',x,'ydata',y);
axis([-1 1 -1 1])
pause(0.01);
end
9. Optional: Julia Set Animation. In this problem, we will animate the Julia Set problem from
Homework 3. If you haven’t done the Julia Set problem in HW3, you can still do this one
because the julia program has to be rewritten anyway. To review: two complex numbers z0
and c define a recursive relationship for subsequent values of 𝑧𝑛 with n = 1, 2,3... :
2
𝑧𝑛 = 𝑧𝑛−1 +𝑐

The escape velocity of a particular z0 is equal to the time step n at which l𝑧𝑛 l > 2 . You will
write a program to compute the escape velocities of an entire grid of z0 values. To make the
animation look cool, we’ll have to do things a bit differently than they were done in HW3: in
HW3, you computed the escape velocity of a particular z0 , then moved on to the next z0 and
computed its escape velocity, etc. In this version of the program. We’ll compute zn+1 for the
entire grid of z0 ’s, and for each n, find and mark all the z0 ’s that ‘escape’ for that n and
display them. The following steps will lead you to this end
function juliaAnimation(zMax,c,N)
res=500; temp=linspace(-zMax,zMax,res);
[R,I]=meshgrid(temp,temp);
Z=R+1i*I;
M=N*ones(size(Z));
figure
for n=1:N
Z=Z.^2+c;
inds=find(abs(Z)>2);

M(inds)=n;
Z(inds)=nan;
imagesc(temp,temp,atan(0.1*M));
axis xy
drawnow
end

Você também pode gostar