Clear Filters
Clear Filters

Returning the results of a function in a matrix

1 view (last 30 days)
Hi there,
I am currently writing a program to predict default probabilities. My problem is that I need the function to be repeated for "i" times for each "T" and I would like to get the results of the simulation collected in a "i x T" matrix. So far I could not solve that problem and I would be happy if someone could give me a hint how to get a "NumberofDefault" matrix, that can be used for further analysis. I attached a sample, that is not meant to be financially correct, but hopefully illustrates what I did and what I need.
% function [NumberofDefaults]=Diffusion(T)
%%Setting the Variables
n = T*100 % 100 steps for each time period
M = 10000; % Number of Monte Carlo Steps
r = 0.05; % Riskless Interestrate
sigma = 0.1; % Volatility
phi = 0.02; % Change of the barrier
%%Creating the Random variable
x=randn(n,M)*sigma*T/n + (r-sigma/2-phi)*T/n;
aux1= x;
X = randi([1001,2000],M,1)/1000;
X=log(X);
aux2=[X';aux1];
%%Matrix that is to be analysed
X=cumsum(aux2);
%%Returning all default events
out=arrayfun(@(n) min([ 0 X(find(X(:,M)<0,1),n)]),1:size(X,2));
out2=exp(out(out~=0));
NumberofDefaults = length(out2); % Counting all columns with negative entries of X
Thank you very much in advance for any help and sorry for any effort. Thorsten Erdmann

Answers (1)

A Jenkins
A Jenkins on 29 Oct 2013
If your function above is working, you can just call it from another function as many times as you need. Of course if you are doing a large Monte Carlo this might get slow and you may need to find a way to optimize it.
function NumberofDefaultsMatrix=DiffusionMatrix(idx,T)
% call this with the desired number of iterations at each time period T
% this just initializes the matrix so your code runs faster
NumberofDefaultsMatrix=zeros(idx,T);
% construct the matrix
for tt=1:T % for each time T
for ii=1:idx % run idx iterations
NumberofDefaultsMatrix(ii,tt)=Diffusion(tt);
end
end
end % end DiffusionMatrix(idx,T)
% this is the function you already wrote
function NumberofDefaults=Diffusion(tt)
%rest of your code here...
%...
%...
end

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!