How to write included function into other

1 回表示 (過去 30 日間)
Vadim Potorocha
Vadim Potorocha 2020 年 11 月 14 日
編集済み: Image Analyst 2020 年 11 月 14 日
Hi, i need to
write a function that simulates a coin toss: r = coin_flip (N), where N is the number of tosses, r is a logical vector, r (i) = true if the i-th toss is heads. a function that simulates a coin toss: r = coin_flip (N), where N is the number of tosses, r is a logical vector, r (i) = true if the i-th toss is heads
and
write a function that counts the number of tails dropped: h = sum_tails (r), where r is the vector of results of the coin_flip () function, h is the number of tails.
So this what I've made:
function r = coin_flip(N)
i = rand(1,N);
r = (i > 0.5);
endfunction
function h = sum_tails(r)
h = sum(r < 0.5);
endfunction
How could I use coin_flip value for sum_tails?

採用された回答

Subhadeep Koley
Subhadeep Koley 2020 年 11 月 14 日
First of all define these two functions, coin_flip and sum_tails
function r = coin_flip(N)
i = rand(1, N);
r = (i > 0.5);
end
and
function h = sum_tails(r)
h = numel(r) - nnz(r);
end
Call these functions using this script
% Simulate 100 coin tosses
res = coin_flip(100);
% Count number of tails
numTails = sum_tails(res);
% Display result in command window
disp(['Total number of tails dropped: ', num2str(numTails)])

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by