How to use matrix in workspace in a script

13 ビュー (過去 30 日間)
John
John 2013 年 1 月 4 日
Hi,
I have have the function below saved in a script.
The matrix P is defined in the function.
How could I refer to a matrix P in the workspace instead? It is a 200x200 matrix so I can't type it into the function.
Thank you
function [X] = DTMC_SimulationOne(n)
%This is the vector that will hold the entire realization of the chain.
%For example, X(1) is the initial state (1 in our case), X(2) is the second
%state of the chain, etc.
X = zeros([n+1,1]);
%This is the transition matrix of my imaginary chain. Your transition
%mattrix is different.
P = [ 1/3 2/3 0;
1/4 1/2 1/4;
1 0 0];
%Set the initial condition. The first state is told to be state 1.
X(1) = 1;
%The main FOR LOOP. It runs from 1 through n, and updates the state based
%upon the previous state.
for j = 1:n
%Generate a uniform random variable.
r = rand;
if r < P(X(j),1)
X(j+1) = 1;
elseif r < P(X(j),1) + P(X(j),2)
X(j+1) = 2;
else
X(j+1) = 3;
end
end

採用された回答

Walter Roberson
Walter Roberson 2013 年 1 月 4 日
function [X] = DTMC_SimulationOne(n, P)
if nargin < 2
P = [ 1/3 2/3 0;
1/4 1/2 1/4;
1 0 0];
end

その他の回答 (1 件)

Image Analyst
Image Analyst 2013 年 1 月 4 日
You need to return P in the output argument list:
function [P X] = DTMC_SimulationOne(n)
if you want to refer to it in the workspace of the calling routine. Then you "refer" to is like you do any matrix:
theValueOfAnElementOfP = P(row, column);
Of course P is already able to be referred to in the workspace of the function DTMC_SimulationOne. You do know that there are different workspaces, don't you? Each function has its own local workspace.

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by