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

Answers


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);

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)).


Need Your Help

UIViewcontroller with multiple views

objective-c ios uiviewcontroller dealloc multiple-views

The project currently has a UIviewController called "Dashboard" that acts as the main view of all the application. This main view consists of two subviews on top of it, kind of like a splitview. Th...

A library I am using is opening an input stream and not closing it. How can I close it?

java inputstream

Every few days, I get a SocketException, too many files open. I tracked the issue to a temporary pdf file that is being used during a certain process. The process passes a name of a temporary file ...