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 日

0 投票

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 日
Thanks for answering to this question. My problem is I am trying to store the output of the loop as a string into the vector y. But I am unable to do it. Could you please guide me on how to store the output of this for loop in the vector?
Ali Ajaz
Ali Ajaz 2018 年 3 月 18 日
David Fletcher
David Fletcher 2018 年 3 月 18 日
編集済み: David Fletcher 2018 年 3 月 18 日
for a start you won't be able to store 'Upward' and 'Downward' in a matrix without padding them to the same length (and that length will be a minimum of 8 columns ('Downward' has eight letters) not the one you have pre-allocated in y). Would 'U' and 'D' be enough? If you don't want to pad, or contract them down to a single letter, you can allocate to a cell array instead
Ali Ajaz
Ali Ajaz 2018 年 3 月 18 日
tried, it gives following error: Subscript indices must either be real positive integers or logicals.
David Fletcher
David Fletcher 2018 年 3 月 18 日
Tried what?
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 日

0 投票

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 日
編集済み: David Fletcher 2018 年 3 月 18 日
for iter=1:length(Diff)
if (Diff(iter)>=0)
y(iter)='U'
else
y(iter)='D'
end
end
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

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

カテゴリ

ヘルプ センター および File 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