如何在MATLAB中的for循环中创建一个比率数组?

时间:2013-09-11 23:13:54

标签: arrays matlab loops for-loop

我想使用for循环创建一个音符阵列或矢量。每个音符A,A#,B,C ......等于前一个/下一个的2 ^(1/12)比率。 E.G音符A是440Hz,A#是440 * 2 ^(1/12)Hz = 446.16Hz。

从27.5Hz(A0)开始,我想要一个循环,重复88次以创建一个每个音符频率高达4186Hz的数组,所以看起来像

f= [27.5 29.14 30.87 ... 4186.01]

到目前为止,我已经理解了这一点:

   f  = [];
for i=1:87,
   %what goes here
   %  f = [27.5 * 2^(i/12)]; ?

end

return;

2 个答案:

答案 0 :(得分:4)

在matlab中没有必要为此做一个循环,你可以这样做:

f = 27.5 * 2.^((0:87)/12)

答案:

f =

  Columns 1 through 13

         27.5       29.135       30.868       32.703       34.648       36.708       38.891       41.203       43.654       46.249       48.999       51.913           55

  Columns 14 through 26

        58.27       61.735       65.406       69.296       73.416       77.782       82.407       87.307       92.499       97.999       103.83          110       116.54

  Columns 27 through 39

       123.47       130.81       138.59       146.83       155.56       164.81       174.61          185          196       207.65          220       233.08       246.94

  Columns 40 through 52

       261.63       277.18       293.66       311.13       329.63       349.23       369.99          392        415.3          440       466.16       493.88       523.25

  Columns 53 through 65

       554.37       587.33       622.25       659.26       698.46       739.99       783.99       830.61          880       932.33       987.77       1046.5       1108.7

  Columns 66 through 78

       1174.7       1244.5       1318.5       1396.9         1480         1568       1661.2         1760       1864.7       1975.5         2093       2217.5       2349.3

  Columns 79 through 88

         2489         2637       2793.8         2960         3136       3322.4         3520       3729.3       3951.1         4186

答案 1 :(得分:2)

maxind = 87;
f = zeros(1, maxind); % preallocate, better performance and avoids mlint warnings
for ii=1:maxind
  f(ii) = 27.5 * 2^(ii/12);
end

我将循环变量命名为ii的原因是因为i是内置函数的名称。因此,将其用作变量名称被认为是不好的做法。

另外,在你的描述中你说你要迭代88次,但上面的循环只迭代1到87(包括两者)。如果要迭代88次,请将maxind更改为88。