Recording vectors in for loop, when the loop is running in a range starting with negative numbers

1 view (last 30 days)
I'm trying to record values of cn during a for loop, but I can't seem to index into a vector x using the value for the iteration, because my for loop is running from values -50:50. So It cant index into x at x(1,n). I have no idea how to solve this. Does anyone have any suggestions? Thank you!
clear; clc, clf;
t = 0:0.01:20;
A=2;
T=5;
wo = 2*pi()/T;
nmax = 50;
x = zeros(1,length(-nmax : 1 : nmax));
for n = -nmax : 1 : nmax;
if n ~=0
cn = (A/ (T*-1i*n*wo) ) * (exp(-1i*n*wo*T/2)-1);
else
cn = A/2;
end
x(1,n) = cn;
end

Accepted Answer

Stephen23
Stephen23 on 25 Nov 2021
Edited: Stephen23 on 25 Nov 2021
Data are not indices, do not mix them up.
V = -nmax:1:nmax; % data!!!!
for k = 1:numel(V) % indices!!!!!
n = V(k); % data!!!!
if n ~=0
cn = (A/ (T*-1i*n*wo) ) * (exp(-1i*n*wo*T/2)-1);
else
cn = A/2;
end
x(1,k) = cn; % index!!!!
end
  1 Comment
Ben Robson
Ben Robson on 25 Nov 2021
Brilliant thank you. I'd confused myself becuase in previous examples, the data was the same as the indices. Very good lesson. Thanks!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!