rounding given matrix towards zero and even number??

2 views (last 30 days)
Im given a row matrix which contain negative and decimals values. Im asked to round those negative values into zero and those positive with decimals values to even number using for loops and if statement. how can i accomplish this

Accepted Answer

Image Analyst
Image Analyst on 19 Apr 2015
Here's a start:
a = 10 * rand(1,15)-5
for k = 1 : length(a)
if a(k) < 0
a(k) = 0; % Set negative numbers to 0
else
% Round to nearest multiple of 2
end
end
Since it sounds like homework, I'll let you do the part on rounding to the nearest multiple of 2.
  2 Comments
Victor Seaw
Victor Seaw on 20 Apr 2015
Yes it is homework I don't have Matlab v me so can I type out the code here and hopefully u can tell me whether its an error or will it run. Else.. a=2*round(a/2)..?? Will this work in a if and for case
Image Analyst
Image Analyst on 20 Apr 2015
Here's some results with your formula:
a =
Columns 1 through 11
-3.947 -2.9348 -1.9222 -0.9382 0.050209 1.0485 2.011 3.0917 4.0433 5.0427 6.0029
Columns 12 through 17
7.051 8.0964 9.0275 10.074 11.012 12.077
a =
0 0 0 0 0 2 2 4 4 6 6 8 8 10 10 12 12

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!