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
0 个评论
采纳的回答
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);
更多回答(1 个)
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 个评论
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 Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!