MATLAB Answers

appending element to vector

5 ビュー (過去 30 日間)
shobhit mehrotra
shobhit mehrotra 2015 年 2 月 4 日
コメント済み: Guillaume 2015 年 2 月 4 日
Hello Im a diff function to estimate a derivative(du/dx), however I lose an element as excepted, now I want to add the average value of the derivative to the end of vector (du/dx) such that is the same length as u. Thanks

回答 (2 件)

Guillaume 2015 年 2 月 4 日
That doesn't sound very sensible as you're mixing two different entities into a single variable, but if that's what you want to do:
x = sin(linspace(0, pi, 100)); %for example
d = diff(x);
dwithmean = [d mean(d)]
  2 件のコメント
Guillaume 2015 年 2 月 4 日
Why do they have to have the same number of elements?


Michael Haderlein
Michael Haderlein 2015 年 2 月 4 日
As Guillaume has mentioned, that's not the usual way to go. Assume you want to plot the data (which requires equally sized arrays), these are the common options:
figure, hold all
%best way: shift the x by half dx
%lazy way: just use n-1 x values
%semi-lazy way: add nan (will not be plotted)
dydx=[diff(y)./diff(x) nan];
When you run these lines, you see a shift between the blue line (which is technically correct) and the red/green lines (overlaying).

Community Treasure Hunt

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

Start Hunting!

Translated by