필터 지우기
필터 지우기

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

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

추가 답변 (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 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