Indexing arrays in matlab from 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 t开发者_StackOverflow中文版o 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.
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.
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!
精彩评论