user3342639
user3342639

Reputation: 33

If else statement and selection of certain data only

To describe my problem in easy way is, for example, I have frequency from [1,2,3,4,5,6] and data = [4,7,2,1,4,9] for each of the frequency. I need to make summation only data with frequency from 3-5Hz in MATLAB. How do I want to write code to satisfy my problem? Below is my trial to do the program code but not working.

f=[1,2,3,4,5,6];
data = [4,7,2,1,4,9];

if 3<=f<=5
    sumdata=sum(data);
else
end

Upvotes: 0

Views: 44

Answers (2)

Etienne
Etienne

Reputation: 1012

Try :

f=[1,2,3,4,5,6];
data = [4,7,2,1,4,9];

sumdata = sum(data(3 <= f & f <= 5));

The operation: 3 <= f & f <= 5 give you a logical matrix of the value that met the conditions.

>> 3 <= f & f <= 5    
ans =    
     0     0     1     1     1     0

You can then use this logical matrix to get only the value corresponding to valid index in you data : data(3 <= f & f <= 5) and then, sum them : sum(data(3 <= f & f <= 5)).

Upvotes: 2

Dinesh
Dinesh

Reputation: 2204

You can use

f=[1,2,3,4,5,6];
data = [4,7,2,1,4,9];
validData = data(f <= 5 & f >= 3);
result = sum(validData);

Upvotes: 0

Related Questions