Replace an if-statement by a function?
5 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
采纳的回答
Geoff Hayes
2014-12-30
编辑:Geoff Hayes
2014-12-30
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!