How to check if a matrix has already been created?

5 views (last 30 days)
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
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.
Gabor
Gabor on 28 Feb 2019
Edited: Gabor on 28 Feb 2019
Does not work at R2017a
returns
if(exist matrix == false)
Error: Unexpected MATLAB expression.
This is the correct way:
if(exist ('matrix') == false)
%create matrix
else
%do nothing

Sign in to comment.

Accepted Answer

Jan
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
  1 Comment
Matthew Plummer
Matthew Plummer on 17 Nov 2016
Thanks for the help I have included my code below implementing this. If it is empty I will create it with size 1x1 with value 0 then carry out my comparision in the next loop to populate this matrix.
function maxSplit(improvementValue
persistent improvementStorage
if(isempty(improvementStorage))
disp('Improvement storage is not initialized');
improvementStorage = zeros(1);
end
if(improvementValue > improvementStorage(1,1))
improvementStorage(1,1)= improvementValue;
end

Sign in to comment.

More Answers (0)

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!