Add values to the i-th position of a table/double

조회 수: 26 (최근 30일)
António Gil
António Gil . 2020년 8월 11일
댓글: hosein Javan . 2020년 8월 11일
Hi everyone,
How can I add a values to a double 'x' inside a for cycle?
I do not mean to replace the i-th value itself but to add one value (xsim1) between i»i+1 and one value (xsim2) between i+1»i+2.
For example:
x=data(:,1).'; %1x203 double
y=data(:,2).'; %1x203 double
for i=1:length(x)-2
if angle>100
angle = ... (not relevant);
if angle>100
I hope I am specifying what I am trying to do clearly.
Thank you very much in advance.

채택된 답변

hosein Javan
hosein Javan 2020년 8월 11일
if you are trying to insert xsim1 between x(i) and x(i+1) without any data loss, write this code:
x = [x(1:i), xsim, x(i+1:end)]
the value is injected to your vector meaning that if its previous length was "n" now it is "n+1". notice that if you use this in a for loop, the size of your vector changes periodically. in order to avoid that, you have to preallocate the final vector size. if you do this, then it means rather than inserting value you must assign value which is more efficient.
  댓글 수: 2
António Gil
António Gil 2020년 8월 11일
Thank you for your help, I understand it now!
Only one thing, how do I preallocate a vector when I don't know its final size?
Thank you in avance
hosein Javan
hosein Javan 2020년 8월 11일
you're welcome. the only way is to know the final size. if you don't know the final size, you can estimate it and preallocate a wider space for it and after the loop finishes, cut the remaining unneeded elements. however writing a code has more than one algorithm. think of a better way that does not need this. I think what you're trying to do is to avoid sharp edges in your angle plot by inserting an average of the value before and after it. maybe you think back at how the angle is gained and this time avoid situation like this to happen.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)


Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by