storing loop function output in vector

1 次查看(过去 30 天)
Hi, I have a single column array of some positive and negative values. I am trying to use a loop to segregate them and to store the result in a separate vector. Unable to do ot so far. can anyone help please? This is my code:
Diff=MP_25-MP_60
y=nan(117,1)
for i=Diff(1:117) if i>0 y(i) = ('Upward') else y(i) = ('Downward') end end

采纳的回答

David Fletcher
David Fletcher 2018-3-18
编辑:David Fletcher 2018-3-18
y=Diff>=0
will return a logical array of all elements in Diff that are greater than or equal to 0. You can either just use this as a marker, or if you wish index out all the positive values (and by extension also all the negative values) into separate vectors: -
positives=Diff(y)
negatives=Diff(~y)
  6 个评论
Ali Ajaz
Ali Ajaz 2018-3-18
y=nan(117,1)
for i=Diff(1:117,:) if i>0 y = ('U') else y = ('D') end end

请先登录,再进行评论。

更多回答(1 个)

Ali Ajaz
Ali Ajaz 2018-3-18
y=nan(117,1)
for i=Diff(1:117,:) if i>0 y = ('U') else y = ('D') end end
  3 个评论
David Fletcher
David Fletcher 2018-3-18
You may find that because you pre-allocated y as NaN, when you add 'U' or 'D' you get their numeric codes instead of the letter.
you could pre-allocate y to a character vector instead
y=repmat('U',117,1)
David Fletcher
David Fletcher 2018-3-18
Actually, if you pre-allocate y to 'D' you can lose the else clause in the condition block (since the array is already set to 'D')
y=repmat('D',117,1)
for iter=1:length(Diff)
if (Diff(iter)>=0)
y(iter)='U'
end
end

请先登录,再进行评论。

类别

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