Matlab: How do I create a For Loop to calculate the number of positive and negative numbers in an array?

3 views (last 30 days)
Hi,
I've generated a random whole number 1x20 array consisting of numbers between -40 and 40 with the following:
x = randi([-40 40], 1,20)
The next step is to use a for cycle to check every number in the array and calculate the number of positive and negative numbers, and then generate a new array 'd' in which every position of x that is positive will be a 1 and every negative a -1
Thanks

Accepted Answer

Image Analyst
Image Analyst on 2 Oct 2021
Did you even try a for loop?
Here's a start
count = 0;
for k = 1 : length(x)
if x(k) >= 0
else
end
end
I'm sure you'll be able to figure out the rest.
  1 Comment
John Smith
John Smith on 3 Oct 2021
Hi, I've given it a stab and sorta got it to work like this:
for d=1:length(x)
if x(d) > 0
d = 1
elseif x(d) < 0
d = -1
end
end
What I need to do is put is make an array of 1s and -1s where the positive and negatives are, working on that at the minute but struggling, very new to mathcad

Sign in to comment.

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!