Saving data in a loop as a vector

4 ビュー (過去 30 日間)
sourestdeeds
sourestdeeds 2016 年 11 月 20 日
コメント済み: dpb 2016 年 11 月 20 日
I have a binomial expansion which requests the user to input an x value between (-1,1). I am trying to save the term by term output of the above code into a vector but everything i try gives me an error. I think its perhaps because my n sequence starts at zero? If i try to put binx(n) = .... it throws an error.
I basically just want to save all the passes through the loop in a single vector, currently it only saves the last one. All other examples I've found online don't seem to work in this case.

採用された回答

dpb
dpb 2016 年 11 月 20 日
Indeed, Matlab arrays are immutably 1-based...just compute an index...
N=12; % generalize number terms...
binx=zeros(N+1,1); % preallocate for output
term=binx;
idx=0; % index variable initialize...
for n=0:N
idx=idx+1; % and increment first...
term(idx) = ...
binx(idx) = binx(idx-1) + term;
...
Of course, w/ Matlab, you could compute term() then bin becomes
bin=cumsum(term);
after the loop. This then would cause rearrangement of your output displays, so not necessarily the thing to do here; simply pointing out Matlab vectorized syntax in general...
  3 件のコメント
sourestdeeds
sourestdeeds 2016 年 11 月 20 日
Your answer has clarified why this approach isn't ideal though!
I will try a different method for plotting!
dpb
dpb 2016 年 11 月 20 日
Woops...forgot to special-case the first instance of idx-1; better route would be to compute the first value prior to entering the loop, the run the loop from 1:N, and initializing idx=1 instead of 0.

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

その他の回答 (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