Matlab: Init variable if undefined

How can I declare / assign a variable only if it has never been assigned before?

Context:

I am trying to find k that minimizes the calculateSomeDistance (k) of k function. The minimum distance and the corresponding value of k should be available (i.e. in the area) for later use. How to declare minDistance so that I can check if it has already been initialized before comparing it with the current estimated distance?

% How should I declare minDistance? minDistance=undefined; % Doesn't exist. for ki=1:K, distance=calculateSomeDistance(ki); if(isUndefined(minDistance) || distance < minDistance) minDistance = distance; minK = ki; end end % Here minK and minDistance must be in scope 

Is there a way to assign null / undefined to a variable in matlab / octave and check it later in order to make the first valid assignment?

PS: Initializing minDistance for a very large number is very ugly, not what I'm looking for.

Initialization of minDistance when ki is 1 (i.e., on the first pass) is ok, but still not nice.

+6
source share
1 answer

You can check if a variable exists with exist :

 if ~exist('minDistance','var') minDistance = initValue; end 

If you want the variable to exist in the workspace but in undefined state, you can assign nan (and not a number) and check it with isnan . This would be similar to the solution you propose with a value type that does not explicitly conflict with valid variable values.

+10
source

Source: https://habr.com/ru/post/922059/


All Articles