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 visualizzazione (ultimi 30 giorni)
%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

Risposta accettata

Star Strider
Star Strider il 2 Apr 2015
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 Commenti

Accedi per commentare.

Più risposte (1)

James Tursa
James Tursa il 2 Apr 2015
Modificato: James Tursa il 2 Apr 2015
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 Commenti
Frank_m
Frank_m il 2 Apr 2015
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 il 2 Apr 2015
Modificato: James Tursa il 2 Apr 2015
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).

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by