Manahil
Manahil

Reputation: 265

Negative of a Number in MATLAB

I have to make a function in MATLAB in which when input will be given, output will be the negative of that number. The code that I wrote :

function [p] = negative(q)
% given an input , output will be negative of that input

w = subtract(0,1) ; 
[p] = multiply(q,w) ;
end

The code that I wrote for function subtract is :

function [m] = subtract(n,s)
m = n ;
while s
[m]= decrement(m) ;
s = decrement(s) ;
end
end

Code for multiply is :

function [a] = multiply(x,y)
a = x ;
y = decrement(y) ;
while y
[a]= addition(a,x);
y = decrement(y);
end
end

Function for addition :

 function [a] = addition(b,c)
 % adds b and c 
 a = b ;
 while c
 [a] = increment(a) ; 
  c = decrement(c) ;
 end
 end

Funtion increment code :

 function out = increment(in)
 out = in + 1;
 end

Function decrement is following :

function out = decrement(in)
 out = in - 1;
end

The code which I wrote for function negative should work according to me because I am multiplying the input with -1. But in MATLAB command window nothing is printed out (except w= -1) when I write negative(input) . Why is this and how shall I fix it ? I am NOT allowed to use any operation including ( + , - , * , / , < , > , ==) and neither am I allowed to use for loops. Only thing I can use is assignment ( = ) and while loop.

Upvotes: 2

Views: 368

Answers (2)

Rash
Rash

Reputation: 4336

As mentioned, you have some problems with addition,subtract and multiply, so I tried to avoid them.

Try this one,

function [p] = negative(q)
a = q;
b = q;
a = increment(a);
b = decrement(b);
while b && a
    a = decrement(a);
    b = increment(b);
end
while a
    q = increment(q);
    a = increment(a);
end
while b
    q = decrement(q);
    b = decrement(b);
end
p = q;
end

The idea is to define two variables, a,b same as q then increase one while decreasing the other,

so after the first loop, one of a or b will be 0 and the other will be 2xq(no endless loop!).

Then we could easily use another loop to get -q, since we have 2xq.

It seems to work well.

Upvotes: 1

Akshay Rao
Akshay Rao

Reputation: 342

Firstly, I don't understand why you're writing 50 lines of code for a one line problem. out = -1 .* input;

However, your problem lies here:

function [a] = multiply(x,y)
a = x ;
y = decrement(y) ; % --------------!!!
while y
[a]= addition(a,x);
y = decrement(y);  % --------------!!!
end
end

When y is negative, the loop keeps decrementing it and therefore, it never gets out of the loop.

y will be negative whenever you input a positive number Q in negative(Q).

Upvotes: 2

Related Questions