2017-02-05 5 views
-4

Я не может генерировать гистограмму в Matlab с помощью массиване в состоянии генерировать гистограмму в MATLAB, используя массив

% initialising the five arrays to hold the averages of five probabilities of interests 
ar1=zeros(1,100); 
ar2=zeros(1,100); 
ar3=zeros(1,100); 
ar4=zeros(1,100); 
ar5=zeros(1,100); 

%initialising the variable to count the number of experiments 
k=1; 
while k<=100, 
    %generating the required random numbers for the proble 
    %pi is the probablity in winning the ith game 
    p1=rand(1); 
    p2=rand(1)*p1; 
    p3=rand(1)*p2; 
    p4=rand(1)*p3; 
    %initialising variable to count the number of tournaments 
    count_tour=1; 
    %initialising the variables in order to get the sum of all probabilties of interests and then we can get our respective averages 
    t1=0; t2=0; t3=0; t4=0; t5=0; 
    %starting the loop for 50 tournaments 
    while count_tour<=50, 
     %Total probabilties of winning the ith game 
     W1=p1; 
     W2=p1*(1+p2-p1); 
     W3=(p1*p2*p3)+((p1*p1)*(2-p1-p2))+((p4)*(1-p1)*(1-p1)); 
     %probabilty that player had won the first game given that he won the second game 
     W4=(p1*p2)/W2; 
     %probabilty of winning all three games 
     W5=p1*p2*p3; 
     %getting the sum of all probabilies in 50 tournaments 
     t1=t1+W1; 
     t2=t2+W2; 
     t3=t3+W3; 
     t4=t4+W4; 
     t5=t5+W5; 
     count_tour=count_tour+1; 
    end 
    %getting the averages of probabilties of interest in 50 tournaments 
    av1=t1/50; 
    av2=t2/50; 
    av3=t3/50; 
    av4=t4/50; 
    av5=t5/50; 
    ar1(k)=ar1(k)+av1; 
    ar2(k)=ar2(k)+av2; 
    ar3(k)=ar3(k)+av3; 
    ar4(k)=ar4(k)+av4; 
    ar5(k)=ar5(k)+av5; 
    k=k+1; 
end 
figure(); 
h1=histogram(ar1); 
h2=histogram(ar2); 
h3=histogram(ar3); 
h4=histogram(ar4); 
h5=histogram(ar5); 
+0

Когда я запускаю свой код, как я получаю гистограмму' ar5', что то, что я бы ожидать. Поэтому вам, вероятно, нужно более четко объяснить свою цель. – EBH

ответ

0

Вот более правильная, простая, легко читаемая и рабочая версия коды:

% initialising the five arrays to hold the averages of five probabilities 
% of interests 
ar = zeros(100,5); 
for k = 1:100 
    % generating the required random numbers for the proble 
    % pi is the probablity in winning the ith game 
    p = cumprod(rand(4,1)); 
    % initialising the variables in order to get the sum of all probabilties of interests and then we can get our respective averages 
    t = zeros(1,5); 
    % starting the loop for 50 tournaments 
    for count_tour = 1:50, 
     % Total probabilties of winning the ith game 
     W(1) = p(1); 
     W(2) = p(1)*(1+p(2)-p(1)); 
     W(3) = p(1)*p(2)*p(3)+((p(1)*p(1))*(2-p(1)-p(2)))+((p(4))*(1-p(1))*(1-p(1))); 
     % probabilty that player had won the first game given that he won the second game 
     W(4) = (p(1)*p(2))/W(2); 
     % probabilty of winning all three games 
     W(5) = p(1)*p(2)*p(3); 
     % getting the sum of all probabilies in 50 tournaments 
     t = t+W; 
    end 
    % getting the averages of probabilties of interest in 50 tournaments 
    av = t./50; 
    ar(k,:)=ar(k,:)+av; 
end 
figure(); 
hold on 
for k = 1:size(ar,2) 
    h(k) = histogram(ar(k,:)); 
end 
hold off 

Какой результат в (например):

multi hist

Фактически, ваш внутренний контур вообще не нужен, он ничего не делает, и внешний цикл может быть устранен с использованием элементарной арифметики, поэтому этот код можно укоротить до более эффективной и компактной версии:

% generating the required random numbers for the proble 
% pi is the probablity in winning the ith game 
p = cumprod(rand(100,4)); 
% Total probabilties of winning the ith game 
W(:,1) = p(:,1); 
W(:,2) = p(:,1).*(1+p(:,2)-p(:,1)); 
W(:,3) = p(:,1).*p(:,2).*p(:,3)+((p(:,1).*p(:,1)).*(2-p(:,1)-p(:,2)))+... 
    ((p(:,4)).*(1-p(:,1)).*(1-p(:,1))); 
% probabilty that player had won the first game given that he won the second game 
W(:,4) = (p(:,1).*p(:,2))./W(:,2); 
% probabilty of winning all three games 
W(:,5) = p(:,1).*p(:,2).*p(:,3); 
figure(); 
hold on 
for k = 1:size(W,2) 
    h(k) = histogram(W(k,:)); 
end 
hold off 

без изменения каких-либо вычислений в вашем коде, просто устраняя ненужные циклы и переменные.

1

Предполагая, что секция вычисления массивов ar1, ar2, ar3, ar4, ar5 является правильным, а также с учетом обновления, предложенным в ответе от @EBH, проблема может быть в том, как вы участке гистограмм:

  • сначала открыть фигура
  • вы звоните, в последовательности, 5 раз functin histogram

Это может работать на первой гистограмме, тем не менее, второй один будет сюжет на том же рисунке, и это будет замените первый; то же самое для других.

Возможные решения могут быть:

  • , чтобы каждый histogram на deedicated figure
  • все histogram на одной фигуре

В первом случае достаточно вызвать figure перед каждым позвоните по номеру histogram.

Во втором случае вы можете использовать функцию subplot, чтобы создать 5 осей на одном рисунке, на которых будут построены гистограммы.

В дальнейшем вы можете найти возможную реализацию предлагаемого подхода.

Два флага используется для управления чертежом:

  • same_xy_lim: 1 => установить одинаковый xlim, ylim для всех осей 0 => не изменяет xlim, ylim
  • multi_fig: 1 => участок каждая гистограмма в отдельном рисунке 0 => зарисовывать гистограммы в одном рисунке с помощью сюжетных

заговорщической часть сценария может быть обновлена ​​следующим образом:

% Define and set the flags to control the drawing mode: 
% same_xy_lim: 1 => set the same xlim, ylim for all the axes 
%     0 => do not modify the xlim, ylim 
% multi_fig: 1 => plot each histogram in a separate figure 
%    0 => plot all the histograms in a single figure using 
%     subplot 
same_xy_lim=1; 
multi_fig=1; 

% figure(); 
if(multi_fig) 
    figure 
else 
    subplot(3,2,1) 
end 
h1=histogram(ar1); 
if(same_xy_lim) 
    xlim([0 1]) 
    ylim([0 100]) 
end 

if(multi_fig) 
    figure 
else 
    subplot(3,2,2) 
end 
h2=histogram(ar2); 
if(same_xy_lim) 
    xlim([0 1]) 
    ylim([0 100]) 
end 

if(multi_fig) 
    figure 
else 
    subplot(3,2,3) 
end 
h3=histogram(ar3); 
if(same_xy_lim) 
    xlim([0 1]) 
    ylim([0 100]) 
end 

if(multi_fig) 
    figure 
else 
    subplot(3,2,4) 
end 
h4=histogram(ar4); 
if(same_xy_lim) 
    xlim([0 1]) 
    ylim([0 100]) 
end 

if(multi_fig) 
    figure 
else 
    subplot(3,2,5) 
end 
h5=histogram(ar5); 
if(same_xy_lim) 
    xlim([0 1]) 
    ylim([0 100]) 
end 

Это генерировать, в зависимости от настройки указанных выше флагов:

Все в один рисунок

enter image description here

Одна гистограмма на рисунке

enter image description here

Надеется, что это помогает,

Qapla»