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

1 回表示 (過去 30 日間)
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

採用された回答

Stephen23
Stephen23 2021 年 11 月 25 日
編集済み: Stephen23 2021 年 11 月 25 日
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 件のコメント
Ben Robson
Ben Robson 2021 年 11 月 25 日
Brilliant thank you. I'd confused myself becuase in previous examples, the data was the same as the indices. Very good lesson. Thanks!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by