matlab中数组索引从0开始

发布于 2024-12-07 20:35:13 字数 605 浏览 0 评论 0原文

对于我正在上的数学课,我必须编写一个程序来计算函数的 FFT。我们在课堂上得到了代码。我在 matlab 中输入代码时遇到问题,因为索引从 0 开始。这是课堂上给出的代码:

Input: q,N,f(k)
Output: d(k)

sigma(0) = 0

for r = 0 to q-1
  for k = 0 to (2^r)-1
      sigma((2^r)+k) = sigma(k) + 2^(q-1-k)
  end
end

for k = 0 to N-1
   d(k) = f(sigma(k))/N
end

for r = 0 to q-1
  M = 2^r
  Theta = e^(-i*pi()/M)
 for k = 0 to M-1
   for j = 0 to 2^(q-1-r)-1
     x = theta^(k)*d(2*j*M+k)-x
     d(2*j*m+k) = d(2*j*M+k)+x
   end
 end
end

通常这并不难实现,但是,索引让我失望。如何编写从索引 1 而不是 0 开始循环的代码(该程序必须在 Matlab 中编写)?通常我会手动计算第一项(0 项)并将其放在循环之外,然后将循环移动一个索引。然而这个问题并不那么简单。谢谢。

For the math class I'm taking, I have to write a program to compute the FFT of a function. We have been given the code in class. I'm having problems entering the code in matlab because the index starts at 0. This is the code given in class:

Input: q,N,f(k)
Output: d(k)

sigma(0) = 0

for r = 0 to q-1
  for k = 0 to (2^r)-1
      sigma((2^r)+k) = sigma(k) + 2^(q-1-k)
  end
end

for k = 0 to N-1
   d(k) = f(sigma(k))/N
end

for r = 0 to q-1
  M = 2^r
  Theta = e^(-i*pi()/M)
 for k = 0 to M-1
   for j = 0 to 2^(q-1-r)-1
     x = theta^(k)*d(2*j*M+k)-x
     d(2*j*m+k) = d(2*j*M+k)+x
   end
 end
end

Normally this would not be hard to implement but, the indicies are throwing me off. How do I write this code starting the loops at index 1 instead of 0(the program has to be written in Matlab)? Normally I would just manually calculate the first term(0 term) and put it outside the loop and then, shift the loop by one index. This problem however is not that simple. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无声静候 2024-12-14 20:35:13

每当您对数组进行索引时,只需添加一个即可。例如:

sigma((2^r)+k+1) = sigma(k+1) + 2^(q-1-k)

另外,当您指的是 sqrt(-1) 时,请使用 1i 因为它更清晰、更安全,因为您可以覆盖 i 的含义或 j 意外,而且速度更快。

Just add one whenever you're indexing into an array. For example:

sigma((2^r)+k+1) = sigma(k+1) + 2^(q-1-k)

Also, use 1i when you mean sqrt(-1) since it's clearer, safer, since you can overwrite the meaning of i or j accidentally, and faster.

恋你朝朝暮暮 2024-12-14 20:35:13

我会将每个数组索引作为“i 数组索引”,然后立即将数组索引更改为i 数组索引 - 1。然后你可以使用数组索引作为数学部分,并使用i*数组索引*来索引指定的数组。

示例:

而不是

for i = 0:n
    sum = sum + i*array(i);
end

i 会做

for ii = 1:n+1
    i = ii-1;
    sum = sum + i*array(ii);
end

编辑:极其愚蠢的打字错误:ii 应该从 1:n+1 开始 - 这就是我改变的全部要点!

i would do every array index as "i array index" and then immediately change array index to be i array index - 1. you can then use array index for the mathematical portion and i*array index* to index specified arrays.

example:

instead of

for i = 0:n
    sum = sum + i*array(i);
end

i would do

for ii = 1:n+1
    i = ii-1;
    sum = sum + i*array(ii);
end

EDIT: incredibly stupid typo: ii should go from 1:n+1 - that was the entire point of my change!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文