check a condition once and remember it later in the code
2 views (last 30 days)
Show older comments
I want to check for an input at the beginning of my code.
then when i enter a while loop i don't want to recheck this input,
i want to already know it to save time. for example
function [ W,H,T] = AS_R(Q, X,W,H,options)
% first check
if strcmp(options.type, 'RSI')
[ L,R,X_R,X_L ] = RSI(X,r);
elseif strcmp(options.type, 'GC')
[ L,R,X_R,X_L ] = GC(X,r,nu);
else
disp('Compression type does not exit');
end
while (toc<= options.Tmax)
for i=1:20
%do something
end
% Do Something
%--------MY QUESTION ------------------___%
% At this point i obtain new values, and so i need to call my function
% that i checked for in the beginning but dont want to do the strcmp checks again
% I want matlab to already know my choice from the first instance
[ L,R ,X_R,X_L ] = RPI(X,r); % eg it should already use the RSI since it picked it from start.
k=k+1;
end
end
0 Comments
Accepted Answer
Adam
on 5 Dec 2019
Potentially you can change your if statement to the following, but it depends on what nu is as this does not seem to be defined so would crash anyway on that first call. If it is constant and known in advance then this should work, if it isn't then it is more tricky as you have to pass different arguments to your functions depending which option it is.
if strcmp(options.type, 'RSI')
func = @RSI;
elseif strcmp(options.type, 'GC')
func = @(X,r) GC( X, r, nu )
else
disp('Compression type does not exit');
end
This would allow you to just call
[ L,R,X_R,X_L ] = func( X, r );
later on, if only X and r change in the while loop.
If nu also changes it would need a bit more complicated solution.
4 Comments
Adam
on 5 Dec 2019
I could have done the first one in the same way:
func = @(X,r) RSI( X, r )
but it would be redundant.
The difference is in the fact that for my answer nu is a fixed argument known in advance, so it is effectively 'baked into' the function handle when you create it, while X and r are the variable arguments that get passed in later and are not known at function handle creation time.
In the first case there are only variable arguments so the short-form of the function handle works.
func = @GC( nu )
is not valid syntax though and
func = @() GC( nu )
is valid syntax, but not for what you want as it will create a function of 0 arguments, hence if you need to pass in a static argument you need the full thing.
There is a cell array format too, but I have never bothered to learn that as this method has always worked fine for me and I hate cell arrays!
More Answers (1)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!