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

In C++, how to reuse the code when object relationship isn't intuitive?

c++ inheritance composition code-reuse

Apologies if this is sort of vague, but I don't know how to go about code reuse in the following situation. I'm using C++.

How to search column_names in Vertica?

search vertica

Anyone know of a handy function to search through column_names in Vertica? From the documentation, it seems like \d only queries table_names. I'm looking for something like MySQL's

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.