Course Content
Matlab From Beginner to Professional
Matlab From Beginner to Professional
If Statements
What happens if we want to program different tasks depending on certain conditions? Do we write separate programs for each case? No! We'll use if statements!
If statements allow portions of code to be executed or skipped based on whether or not certain Boolean statements are true or false. This sort of gatekeeping can also be made more intricate through the incorporation of elseif and else statements. And when combined with for loops (previous chapter), we can really start to analyze data in complex and efficient ways.
Here we'll dip our toes in by learning the general behavior and logical errors that can arise. The syntax isn't super complicated, so you can start off with the set of snippets until you have it down, and in the next section we'll start using if statements to analyze data in real world applications.
Task
Write a program that:
- Imports all the data from the Excel file "Chapter 4 Task Data Set";
- Uses an if statement nested in a for loop to identify the indices of all the rows in the data set that represent farms owned by Mary;
- Reduces the numerical data to only the farms owned by Mary;
- Calculates the total number of each type of animal that Mary owns;
- Calculates the average number of each type of animal on Mary's farms;
- Outputs these two sets of calculations to a well-defined location in the Excel file, along with headings to label the results.
Thanks for your feedback!