How do I use a for loop to return a vector
조회 수: 3 (최근 30일)
이전 댓글 표시
Hey everyone, I've been using matlab for about a month, so this might be a pretty simple question.
I have a vector x=[-3.5 -5 6.2 11 0 8.1 -9 0 3 -1 3 2.5], and I want to make two other vectors from it using a for loop. The first contains the positive elements of x, and the second contains the negative elements of x. I can get it to return individual elements, but not vectors. Your help is greatly appreciated, I've been trying to figure this out for a couple hours.
Heres my code
x=[-3.5 -5 6.2 11 0 8.1 -9 0 3 -1 3 2.5];
n=length(x);
for k=1:n
if x(k)>0
P=x(k)
elseif
x(k)<0
N=x(k)
end
end
댓글 수: 0
채택된 답변
Ben11
2014년 7월 31일
편집: Ben11
2014년 7월 31일
Hi Adam,
you actually don't need a loop:
P = x(x > 0);
N = x(x < 0);
P =
6.2000 11.0000 8.1000 3.0000 3.0000 2.5000
N =
-3.5000 -5.0000 -9.0000 -1.0000
If you want to use a loop, you need to assign an index to P and N, otherwise the loop will erase the current value at every iteration. Here's an example;
P = zeros(1,length(x)); % Initialize a vector P of length equal to that of x. After the loop we get rid of the 0 values.
N = P; same thing for N.
for k=1:length(x)
if x(k)>0
P(k) =x(k);
elseif x(k)<0
N(k)=x(k);
end
end
P(P==0) = []; % Remove values equal to 0
N(N==0) = [];
댓글 수: 3
Ben11
2014년 7월 31일
Yep. Since normally you would not know beforehand how many values there would be in P and N, it is good practice to initialize the vector with a size large enough to store more values. Anyhow, at each loop iteration you add the current value of x in either P or N depending on its value. Glad to help!
추가 답변 (0개)
참고 항목
카테고리
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!