0% found this document useful (0 votes)
42 views

Homework 4

The document provides instructions and code for several MATLAB assignments involving random number generation, probability simulations, data visualization, and image processing. The assignments include: 1) generating random numbers from normal and Poisson distributions and verifying statistics, 2) simulating a coin flip experiment and plotting the results, 3) creating and manipulating cell and structure arrays, 4) practicing with figure handles to customize plots, and 5) reading and modifying an image file.

Uploaded by

alex
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Homework 4

The document provides instructions and code for several MATLAB assignments involving random number generation, probability simulations, data visualization, and image processing. The assignments include: 1) generating random numbers from normal and Poisson distributions and verifying statistics, 2) simulating a coin flip experiment and plotting the results, 3) creating and manipulating cell and structure arrays, 4) practicing with figure handles to customize plots, and 5) reading and modifying an image file.

Uploaded by

alex
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

HOMEWORK 4

INSTRUCCIONES. Elabora un vector de 500 nmeros aleatorios de una distribucin normal con
media 2 y desviacin estndar de 5. Verifica la desviacin estndar y la media utilizando
(mean,std).

Cdigo.

%Random numbers.
%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).

%Generate the vector with 500 random numbers, mean of 2 and std deviation
%of 5.
r = 2 + 5.*randn(500,1)

dev = std(r)

med = mean(r)

PRCTICA 2.

INSTRUCCIONES. Elabora un script llamado coinTest.m que simule el modelo secuencial de una
moneda que es lanzada 5000 veces. Registra cada vez que se obtiene heads y grafica el
estimado de probabilidad de obtener dicho valor con esta moneda. Grafica esta estimacin
junto con una lnea horizontal en el valor esperado de 0.5.

Cdigo.

%Declare the number of coinflips.


n=5000;

%
r = randi([0,1],1,n)

%Get the cumulative values.


res = cumsum(r)

%Plot the data.


figure

%Divide the cumulative values individually by the number of points from 1


%to 5000.
Plot (res ./ (1:n),'r','lineWidth',2)

%Retain the data so that it doesn't get erased by the second plot.
hold on

%Plot a line at 0.5 to indicate the desired value.


plot(0:4999,0.5,'b','lineWidth',2)

%Add legend to the lines.


Legend ('Probability calculated.','Fair coin.')

%Add markings to the table.


Title ('Sample probability of Heads in a coin simulation.')
xlabel('Trials')
ylabel('Probability of heads')

%Add grid
grid on
axis([0 5000 0 1])

Resultado.

Sample probability of Heads in a coin simulation.


1
Probability calculated.
Fair coin.
0.9

0.8

0.7
Probability of heads

0.6

0.5

0.4

0.3

0.2

0.1

0
0 500 1000 1500 2000 2500 3000 3500 4000 4500 5000
Trials

3.
INSTRUCCIONES. Elabora una distribucin de Poisson de 1000 nmeros distribuidos con
parmetro lamdba 5.

Cdigo.
%Declare lambda
value. lambda = 5;

%n
n = 1:1000;

%Generate the Poisson


distribution. r =
poissrnd(lambda,1000,1);

%Generate the histogram.


[x,c] = hist(r,13); %D is your data and 13 is number of bins.
h = x/sum(x); %Normalize to unit length. Sum of h now will be 1.

%Generate bar graphs with 13 values according to the number of analysis


%points.
bar(1:13,h)
;

%Keep the result along with the rest of the data from other plots.
hold on

%Generate the Poisson probability mass function.


p = poisspdf(1:13,5);
[a,b] = hist(p);

%Make a line plot of the real Poisson mass function.


plot(1:13,p,'r','lineWidth',2)

%Add grid, labels and tags.


grid on
title('Poisson distribution / mass function.')
xlabel('Samples.')
ylabel('Distribution values.')
legend('Distributed Poisson','Poisson mass function')

Resultado.
Poisson distribution / mass function.
0.18
Distributed Poisson
0.16 Poisson mass function
0.14

Distribution values. 0.12

0.1

0.08

0.06

0.04

0.02

0
1 2 3 4 5 6 7 8 9 10 11 12 13
Samples.

INSTRUCCIONES. Prctica con celdas.

a. Elabora una celda de 3x3 donde la primera columna contenga los nombres Joe, Sarah
y Pat; la segunda columna Smith, Brown y Jackson y la tercera columna contenga
sus salaries $30,000.00, $150,000.00 y $120,000.00. Muestra los resultados utilizando
disp.
%Title.
disp('cellProblem'
)

%Declare the cell values.


cell = {'Joe', 'Smith', 30000; 'Sarah', 'Brown', 150000; 'Pat',
'Jackson', 120000};

%Diplay it using disp even though it can be done automagically, as asked


in
%the exercise.
disp(cell)
b. Sarah se casa y cambia su appelido a Meyers. Realiza este cambio en la celda que
elaboraste.

%Change the values of element 2,2 of the cell from 'Brown' to 'Meyers'.
cell{2,2} = 'Meyers';

c. Pat recibe una promocin y tiene un aumento de $50,000.00. Cambia su salario


aadiendo esta cantidad al valor correspondiente en la celda.

%Diplay it using disp even though it can be done automagically, as asked


in
%the exercise.
disp(cell)
%Add the raise to Pat's salary.
cell{3,3} = 120000+50000;

%Diplay it using disp even though it can be done automagically, as asked


in
%the exercise.
disp(cell)

INSTRUCCIONES. Uso de estructuras.

a. Obtn el contenido de tu directorio actual. a es un arreglo estructura. Cul es su


tamao? Cules son los nombres de los campos en a?

%Check what's in the actual


dir. a = dir

%Iterate to check is the data is a directory or


not. ct = 0;
x = 0;
for i = 1: length(a)
if(a(i).isdir ==
0)
%If a(i) isn't a directory, indicate it and add to the
count. disp('Archivo encontrado. Contador ++');
ct = ct +
1;

if(x ==
0) x
= 1;
y =
i;
end
%Get the number of bytes and filename.
b(i).name = a(i).name;

%Get file size.


End

End
b(i).size = a(i).byte

b. Elabora un ciclo para acceder a todos los elementos de a y, si no son un directorio,


muestra la siguiente frase: File filename contains X bytes donde filename es el nombre
del archivo y X el nmero de bytes de ste.

%Display number of files found.


fprintf('\n\n');
fprintf('Se encontraron %d archivos.\n\n',ct);
c. Elabora una funcin llamada displayDir.m que mostrar los tamaos de los archivos del
directorio en el cual es ejecutada.
%Display name and file
size. for i=y : length(b)
fprintf('El archivo %s contiene %d bytes.\n',b(i).name, b(i).size);
end

PRCTICA 6.

INSTRUCCIONES. Uso de handles.

a. Elabora un script llamado handlesPractice.m


b. Elabora una variable x de 0 a 2*pi y obtn
y=sin(x). c. Elabora una nueva figura y grafica
(x,y,r).
d. Establece el lmite de x de 0 a pi.
e. Establece la propiedad xtick en el eje para que vaya de los valores [0 pi 2pi] y la etiqueta
xticklabel de {0, 1 2}.
f. Establece la propiedad ytick con los valores -
1:.5:1. g. Activa la gradilla.
h. Cambia el color de los indicadores en el eje y a verde y de los indicadores x a azul.
Cambia el fondo a negro.
i. Cambia la propiedad de color de la figura a gris oscuro.
j. Aade ttulo One sine wave from 0 to 2 con tamao de letra 14, en negrita y color
blanco.
k. Aade las etiquetas x & y adecuadas con color cyan y verde respectivamente, tamao
de letra 12.

%Create the x & y variables where x goes from 0 to 2*pi and y is the sin
of
%such function.
x = 0:0.1:2*pi;
y = sin(x);

%Plot the information with red outline.


plot(x,y,'r')

%Set xlimit.
xlim([0 2*pi])

%Set the handle h.


set(gca,'XTick',[0 pi 2*pi])
set(gca,'XTickLabel',{'0','1','2'})
set(gca,'YTick',[-1:0.5:1])

%Activate the grid.


grid on

%Change color for X and Y axis.


set(gca,'Xcolor','c')
set(gca,'Ycolor','g')

%Change background color.


set(gca,'Color','k')
%Set title.
title('One sine wave from 0 to
2\pi.','fontSize',14,'fontWeight','bold','color','white')

%Set xlabel and ylabel.


xlabel('x values in term of \pi','fontSize',12,'color','c')
ylabel('sin(x)','fontSize',12,'color','c')

%Image processing
format longg;
format compact;
fontSize = 20;
% Read in a standard MATLAB color demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'peppers.png';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
% Didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
rgbImage = imread(fullFileName);
% Get the dimensions of the image. numberOfColorBands should be = 3.
[rows columns numberOfColorBands] = size(rgbImage);
% Extract the individual red, green, and blue color channels.
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
blackImage = uint8(zeros(rows, columns));
newRedChannel = [redChannel, redChannel; blackImage, blackImage];
newGreenChannel = [greenChannel, blackImage; greenChannel, blackImage];
newBlueChannel = [blueChannel, blackImage; blackImage, blueChannel];
newRGBImage = cat(3, newRedChannel, newGreenChannel, newBlueChannel);
% Display the original color image.
imshow(newRGBImage, []);
title('New Color Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);

% Animation: Brownian motion

% Demo to do a random walk in 2 dimensions.


% User is asked for the number of steps to take.
% By Image Analyst
clc; % Clear the command window.
clearvars;
close all; % Close all figures (except those of imtool.)
workspace; % Make sure the workspace panel is showing.
fontSize = 20;
format compact;
% Ask user for a number of steps to take.
defaultValue = 15;
titleBar = 'Enter an integer value';
userPrompt = 'Enter the number of steps to take: ';
caUserInput = inputdlg(userPrompt, userPrompt, 1, {num2str(defaultValue)});
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
integerValue = round(str2num(cell2mat(caUserInput)));
% Check for a valid integer.
if isnan(integerValue)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
integerValue = defaultValue;
message = sprintf('I said it had to be an integer.\nI will use %d and continue.',
integerValue);
uiwait(warndlg(message));
end
numberOfSteps = integerValue;
deltax = rand(numberOfSteps) - 0.5;
deltay = rand(numberOfSteps) - 0.5;
xy = zeros(numberOfSteps,2);
for step = 2 : numberOfSteps
% Walk in the x direction.
xy(step, 1) = xy(step, 1) + deltax(step);
% Walk in the y direction.
xy(step, 2) = xy(step, 2) + deltay(step);
% Now plot the walk so far.
xCoords = xy(1:step, 1);
yCoords = xy(1:step, 2);
plot(xCoords, yCoords, 'bo-', 'LineWidth', 2);
hold on;
textLabel = sprintf('%d', step);
text(xCoords(end), yCoords(end), textLabel, 'fontSize', fontSize);
end
% Mark the first point in red.
hold on;
plot(xy(1,1), xy(1,2), 'rs', 'LineWidth', 2, 'MarkerSize', 25);
textLabel = '1';
text(xy(1,1), xy(1,2), textLabel, 'fontSize', fontSize);
grid on;
% Mark the last point in red.
plot(xCoords(end), yCoords(end), 'rs', 'LineWidth', 2, 'MarkerSize', 25);
title('Random Walk', 'FontSize', fontSize);
xlabel('X', 'FontSize', fontSize);
ylabel('Y', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Calculate the distance from the origin.
distanceFromOrigin = hypot(xCoords(end), yCoords(end));
message = sprintf('Done with demo!\nDistance of endpoint from origin = %.3f',
distanceFromOrigin);
msgbox(message);

You might also like