Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab: Init variable if undefined

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

Context:

I'm trying to find k which minimizes a function calculateSomeDistance(k) of k. The minimal distance and the corresponding k value should be available (ie. in scope) for later use. How should I declare minDistance so that I can check whether it was already initialized before comparing it to the currently calculated 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 a null/undefined value to a variable in matlab/octave and later test for it in order to make the first valid assignment?

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

Initializing minDistance when ki is 1 (ie. on first pass) is OK, but still not nice.

like image 579
Philipp Avatar asked Aug 03 '12 15:08

Philipp


1 Answers

You can check whether a variable exists using exist:

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

If you want to have the variable exist in the workspace, but in an undefined state, you can assign nan (not a number) and check for that with isnan. This would be similar to the solution you've proposed, with a value type that is explicitly not going to conflict with any valid values of the variable.

like image 64
tmpearce Avatar answered Sep 28 '22 18:09

tmpearce