When MATLAB scans through cases in a switch/case
block, does it remember the values that it skips, and is it possible to access that list? I have a few functions with long switch\case
block and I would like to have them return a list of valid case values if they make it down to otherwise
. For instance, I have a function that returns a set of optical constants for a material. It currently has about 20 different materials and it is growing as I consider new ones.
I realize I can brute-force it and just re-type all of the valid cases into a cell array under otherwise
and have the function throw an error and return the list of valid responses, but maintaining both lists without errors or laziness creeping in over time is challenging.
To clarify, it sounds like what you are asking to do is something like the following:
value = 'z';
output = [];
switch value
case 'a'
output = 1.234;
case 'b'
output = 2.345;
case 'c'
output = 3.456;
otherwise
output = [];
disp('Please use one the the following values: a, b, c')
%It would be nice to auto-populate that string wouldn't it?
end
That is not directly possible in Matlab (or any language I am aware of).
However, if you move from a switch/case statement to a more data-centric code design, it becomes easy. For example, the above code can be re-written as:
%Setup (this can be preloaded and stored as persistent if too time consuming)
count = 1;
allvalues(count).name = 'a'; allvalues(count).value = 1.234; count = count+1;
allvalues(count).name = 'b'; allvalues(count).value = 2.345; count = count+1;
allvalues(count).name = 'c'; allvalues(count).value = 3.456; count = count+1;
%Lookup
value = 'z'; %Also try value = 'a'
maskMatch = strcmp({allvalues.name},value);
if any(maskMatch)
output = allvalues(maskMatch).value;
else
disp('Please use one of the following values:');
disp({allvalues.name});
end
This is an example of using an array-of-structures to store data. There are many ways to use Matlab data structures to store this kind of data, e.g. a Map or a cell array. For a somewhat comprehensive list, see answers to this question: MATLAB Changing the name of a matrix with each iteration
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With