I am trying to create two vectors out of one,x, where one will contain all the positive elements and the other all the negative elements.

1 回表示 (過去 30 日間)
%this program creates vectors N and P out of x
%N will contain negative elements and P the positive elements
x=[-3.5 -5 6.2 11 0 8.1 -9 0 3 -1 3 2.5];
for k=length(x);
if x>=0
k=x
P(k)=k
else x<0
N(k)=k
end
end
P
N

採用された回答

Star Strider
Star Strider 2015 年 4 月 2 日
Just use ‘logical indexing’:
x=[-3.5 -5 6.2 11 0 8.1 -9 0 3 -1 3 2.5];
P = x(x >= 0);
N = x(x < 0);
  15 件のコメント
Frank_m
Frank_m 2015 年 4 月 2 日
Thanks again, this was very helpful.

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

その他の回答 (1 件)

James Tursa
James Tursa 2015 年 4 月 2 日
編集済み: James Tursa 2015 年 4 月 2 日
You are using k as a loop variable but only doing one iteration, k = 12. Maybe you want this result:
P = x(x>0);
N = x(x<0);
Or if you want them to retain their original spots, something like this
P = x;
P(~(x>0)) = 0;
N = x;
N(~(x<0)) = 0;
EDIT:
If you have to use loops, then change your looping index to the following:
for k=1:length(x)
And inside your loop, don't use x by itself in the test since that is the entire vector x. Instead, use the k'th element of x (i.e., use your k index). E.g.,
if x(k) >= 0
Finally, Don't change the value of k inside your loop! That will mess up the looping. So get rid of this line:
k=x
And then use x(k) on the right hand side of your assignments instead of k.
  3 件のコメント
Frank_m
Frank_m 2015 年 4 月 2 日
It seemed to solve the problem, P is now a vector but vector N is not coming out.
%this program creates vectors N and P out of x
%N will contain negative elements and P the positive elements
x=[-3.5 -5 6.2 11 0 8.1 -9 0 3 -1 3 2.5];
for k=length(x);
if x(k)>=0
P = x(x>0);
else x(k)<0
N=x(x<=0)
end
end
P
N
P =
6.2000 11.0000 8.1000 3.0000 3.0000 2.5000
N =
1 2 3 4 0 0 0 0 0 0 0 12
James Tursa
James Tursa 2015 年 4 月 2 日
編集済み: James Tursa 2015 年 4 月 2 日
LOL. Well, if you just change your else statement to this (i.e., drop the x(k) < 0 part) you will have something:
else
However, your "loop" is basically solving the entire problem in a vectorized manner at each iteration! So, this is not really in the spirit of the looping requirement.
I would take a look at Star Strider's comment since he has it basically laid out for you in detail (although it looks like he needs to fix the else line as well).

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

カテゴリ

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