MATLAB week 4

 

Genaro Rivera

10/04/2022

TRAIN scholarship week 4 MATLAB

If/else statements






This week, I learned to use if/else statements. If/else statements are integral for coding, so I enjoyed learning to use if/else statements. Here, I created a script that displays what grade average a student got. Firstly, I used the randi function to generate a random number from 1-100. Secondly, I created an if statement with different branches. MATLAB reads the elseif statements from top to bottom until it runs into a true statement. For example, if the grade average is an 85, it detects AVG<60, AVG<70, and AVG>=70 && AVG<80 as false. It moves on and computes AVG>=80 && AVG<90 as true, so it stops there and displays it. Like I said, MATLAB reads top to bottom until it finds a true statement and reacts to the command. If it finds a true statement and the statement right after is also true, MATLAB will only compute the first one it saw (first come first serve). In conclusion, my code reads the if AVG<60. If true, it will display “Grade is an F.” If false, it will continue to read elseif AVG<70. If true, it will display “Grade is a D”. If false, it will continue to the next elseif until it finds a true statement. (Note: the && does what its English counterpart suggests. AVG>=70 AND AVG<80 for the statement to be true).

If, elseif, and else differ. The best way I could explain it is, if I put an “if” in line one and “if” in line 100 with a bunch of elseif statements in between, if the first “if” statement is false, MATLAB will skip the elseif statements in between and go to line 100 and evaluate the second “If” statement. If the first “if” statement is true MATLAB will evaluate that one and ignore the one in line 100. You must have and “end” statement to separate the two major “if” statements. Else is optional. It serves to tell MATLAB what to display in every other possible scenario not atoned for so that it does not simply return an error message. If acts as the main base, elseif acts as sub features, and else acts as support.

Right now, I cannot think of many useful applications of this feature, but this is just to get the hang of it. More complicated applications exist that build off the basic understanding of this function.




Next, I used a while loop. While loop repeats until the statement is false. To read the statement above, you would say, “while a does NOT equal b, subract 1 from b and multiply a by 2.” Eventually the two values become equal. In this case, they became equal on the 3rd step with a value of 8; eleven minus one repeated three times gives 8 and 1 times 2 repeated three times gives 8.

Step #

a

b

0

1

11

1

2

10

2

4

9

3

8

8

Comments

Popular posts from this blog

Weather Balloon Spring Flight

System Block Diagrams Introduction Week 5

Temperature Sensor week 8