Negating negative values in a matrix using for and if loops in Matlab

Hey I'm new here so sorry if this question has already been answered. I couldn't find out anything about it.
The problem: As it stands, I'm trying to write a program in MATLAB that takes a list of values input by the user and runs them through various functions. I don't want it to accept negative values at all.
What I have so far:
m = input('Please enter values as a row vector \n');
n = length(m);
for k = 1:n
if m(k) > 0;
m(k) = m(k);
else m <= 0;
m(k) = 0;
end
end
m
Any advice would be appreciated.

 Accepted Answer

mean_without_negatives = mean(m(m>=0));

6 Comments

Sean,
Thanks for the quick response but this code isn't really what I had in mind. I need an array without negative values or the 0 placeholders, not just to take the average, but also to plot, run through functions, etc.
Basically, if the input value is 0 or below I need it to not be in the output array.
newm = m(m>0);
then mean(newm) or whatever.
Really appreciate that guys! Thanks.
I know I'm beating a dead horse here but is there a way to implement this still using the for and if loops?
Sure is. But that sounds like an assignment question, and we avoid giving direct answers to assignment questions.
Use two matrices. Only store from one to the other if the data is proven good. Keep track of the current positions in the matrices independently.
By the way, be careful about NaN.
You caught me. It's part of a project. That aside, I don't mind that you're not just giving me an answer, I wouldn't learn from that anyway.
I just very little experience with programming (this is a 1 credit intro class and we spent about 30 minutes on programming) and don't really know how to approach this problem. I'll try to work my way through it with your advice.
Thanks one last time.

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!