Inside Collection (Course): Freshman Engineering Problem Solving with MATLAB

Summary: This module provide several practice exercises on the use of for-loops.

Frequency is a defining characteristic of many physical phenomena including sound and light. For sound, frequency is perceived as the pitch of the sound. For light, frequency is perceived as color.

The equation of a cosine wave with frequency

Suppose that we wish to plot (on the same graph) the cosine waveform in Exercise 1 for the following frequencies: 0.7, 1, 1.5, and 2. Modify your solution to Exercise 1 to use a for-loop to create this plot.

The following for-loop is designed to solve this problem:

```
t=0:.01:4;
hold on
for f=[0.7 1 1.5 2]
y=cos(2*pi*f*t);
plot(t,y);
end
```

The following code changes the line style of each of the cosine plots.

```
fs = ['r-';'b.';'go';'y*']; %Create an array of line style strings
x=1; %Initialize the counter variable x
t=0:.01:4;
hold on
for f=[0.7 1 1.5 2]
y=cos(2*pi*f*t);
plot(t,y,fs(x,1:end)); %Plot t vs y with the line style string indexed by x
x=x+1; %Increment x by one
end
xlabel('t');
ylabel('cos(2 pi f t)')
title('plots of cos(t)')
legend('f=0.7','f=1','f=1.5','f=2')
```

Suppose that you are building a mobile robot, and are designing the size of the wheels on the robot to achieve a given travel speed. Denote the radius of the wheel (in inches) as

1 | 1 |

1 | 2 |

2 | 3 |

4 | 1 |

2 | 2 |

This solution was created by Heidi Zipperian:

```
a=[1 1 2 4 2]
b=[1 2 3 1 2]
for j=1:5
c=sqrt(a(j)^2+b(j)^2)
end
```

```
a=[1 1 2 4 2]
b=[1 2 3 1 2]
c=sqrt(a.^2+b.^2)
```

- « Previous module in collection Programming with M-files: For-Loop Drill Exercises
- Collection home: Freshman Engineering Problem Solving with MATLAB
- Next module in collection » Programming with M-files: A Modeling Example Using For Loops