Replace an if-statement by a function?

1 回表示 (過去 30 日間)
Sam
Sam 2014 年 12 月 30 日
編集済み: Geoff Hayes 2014 年 12 月 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?

採用された回答

Geoff Hayes
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 件のコメント
Sam
Sam 2014 年 12 月 30 日
doesn't work...
Geoff Hayes
Geoff Hayes 2014 年 12 月 30 日
right - I forgot to add in the input parameters...

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by