How to check if a matrix has already been created?
5 views (last 30 days)
Show older comments
I have a function that will be looped through as the functions call each other i.e. function1->function2->function3->function1 etc.
In one of these functions I want to create a matrix that will store a variable for comparison, however this matrix should be retained during all cycles of the program therefore I only want to create this matrix once.
See pseudocode below for what I want to achieve.
if(exist matrix == false)
%create matrix
else
%do nothing
The use of this is to store an improvement value for splitting a data set. See below:
if(improvementValue > improvementStorage(1,1))
improvementStorage(1,1)= improvementValue;
end
(improvementStorage being the matrix I want to create on the first iteration only.)
Any help on how to create this matrix once and not overwriting it with each program iteration would be appreciated.
2 Comments
Adam
on 17 Nov 2016
The obvious solution would be to create a class then this could simply be a property of the class and you can set it or update it when you choose and it will always be available to all functions of the class. If you are not familiar with Matlab OOP though this may be too much work.
Accepted Answer
Jan
on 17 Nov 2016
You can either define a variable which is included in the inputs and outputs of all functions. Then you have full control from anywhere.
Or you can use a persistent variable in one function:
function out = myFunc(In)
persistent M
if isempty(M)
disp('M is not initialized');
end
M = rand(2);
end
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!