check a condition once and remember it later in the code

2 views (last 30 days)
fadams18
fadams18 on 5 Dec 2019
Commented: fadams18 on 5 Dec 2019
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

Accepted Answer

Adam
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

Sign in to comment.

More Answers (1)

fadams18
fadams18 on 5 Dec 2019
So i modified @Adam's answer. I edited the two functions GC and RSI
so that they both have same number of inputs
if strcmp(options.type, 'RSI')
func = @RSI;
elseif strcmp(options.type, 'GC')
func = @GC;
else
disp('Compression type does not exit');
end
[ L,R,X_R,X_L ] = func( X,options);
in that case when if i want GC i pass in eg.
options.type='GC'
options.nu=nu;
options.r=r;
  1 Comment
Adam
Adam on 5 Dec 2019
Yep, that works fine for dealing with the issue of different numbers of input arguments, assuming options already contains nu and doesn't have to assign it to the strcut only in the one case.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!