henberry
henberry

Reputation: 3

function that takes a vector and returns negative numbers and position

I'm looking to create a function that will take a vector and return all the negative values in one vector and their position in another vector. So, for example,

% output:
v = [-1 4 6 2 -3]

% output:
vneg = [-1 -3]
pos  = [1 5].

any help is appreciated!

Upvotes: 0

Views: 204

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38052

Just to complete @WasiAhmad's answer:

function [vneg, pos] = find_negatives(V)

    pos  = find(V < 0);
    vneg = V(pos);

end

Upvotes: 0

Wasi Ahmad
Wasi Ahmad

Reputation: 37771

One simple solution to get the negative values and their index.

x = [4 3 -2 9 -7 31];

index = find(x<0);
-> index = 3 5

x_new = x(index);
-> x_new = -2 -7

Just change the condition in the find function as per your requirement.

Upvotes: 3

Related Questions