Clear Filters
Clear Filters

Replace an if-statement by a function?

3 views (last 30 days)
Sam
Sam on 30 Dec 2014
Edited: Geoff Hayes on 30 Dec 2014
I've got this type of code:
for welke_pp=1:5 %for loop for 5 subjects
for i_testen=1:5 %for 5 measurements
if ~( ((i_testen == 4) && (welke_pp == 1)) || ((i_testen == 4) && (welke_pp == 3)) || ((i_testen == 4) && (welke_pp == 4)) || ((i_testen == 4) && (welke_pp == 5)) || (i_testen == 5) ); %these are the specific tests of a specific subject that shouldn't be included in my calculations.
...
end
end
end
The if-statement is very long, and returns several times throughout my code. I was thinking maybe I could make a function of it and replace the if-statement in my main code by this function. But it didn't work out as I expected. Help?

Accepted Answer

Geoff Hayes
Geoff Hayes on 30 Dec 2014
Edited: Geoff Hayes on 30 Dec 2014
Sam - why didn't he function work out as expected? If you wish to replace the conditions with a function, then just create a function with two inputs and one output (which tells you whether the conditions are satisfied are not). Something like
function [bool] = testIsValid(welke_pp,i_testen)
bool = ~( ((i_testen == 4) && (welke_pp == 1)) || ((i_testen == 4) && (welke_pp == 3)) || ((i_testen == 4) && (welke_pp == 4)) || ((i_testen == 4) && (welke_pp == 5)) || (i_testen == 5) );
And that is it - your conditions decide the value of bool, and your if statement becomes
if testIsValid(welke_pp,i_testen)
% do stuff
end
try the above and see what happens!
  2 Comments
Geoff Hayes
Geoff Hayes on 30 Dec 2014
right - I forgot to add in the input parameters...

Sign in to comment.

More Answers (0)

Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!