简体   繁体   中英

Conditional statement in matlab function argument

I am wondering if its possible to have conditional statements in a function argument. for ex, testarray = [1,5,8,5,7,23,61,16]

psum = sum(testarray>2 & testarray<10)

will it possible to implement something like this in matlab.

I would really appreciate an example.

Yes, please see the example below using your data.

testarray = [1,5,8,5,7,23,61,16]; % your array 

Find sum of all numbers greater than 2 and less than 10 in testarray

psum = sum(testarray(testarray>2 & testarray<10));

The idea is that you find the indices of the numbers that meet the condition (ie, testarray>2 & testarray<10 in this case), extract the numbers by indexing into testarray, and then sum them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM