MATLAB: How to define the own signum function

signum

Hello all,
I am trying to better my programming skills with MATLAB. I wanted to see if I could create my own set of instructions that perform exactly like the signum function does. For example,
X = [-3 0 4];
Y = sign(X)
Y =
-1 0 1
Your answer gets put in an array.
I tried doing this by using if constructs. I only got it to work when the user puts in a single number. Here's my work:
prompt = 'Give a number: ';
result = input(prompt);
X = result;
if X < 0
Y = -1
elseif X == 0
Y = 0
else
Y = 1
end
I don't know how to have someone input an array (like [-3 0 4] ). I also don't know how to have my answer display as an array. Could someone help?

Best Answer

Anthony, looking good. Put the code into a function and use inputdlg to allow inputting the numbers more easily. Alternatively, you could simply let the user define the matrix X and use it as an input for the function.
function Y = my_sig()
prompt = {'Input dialog'};
name = 'Input dialog';
Xcell = inputdlg(prompt, name);
X = str2num(Xcell{1});
Y = zeros(size(X));
for ii = 1:numel(X) % loop through all elements of the vector
if X(ii) < 0
Y(ii) = -1;
elseif X(ii) == 0
Y(ii) = 0;
else
Y(ii) = 1;
end
end
end
Related Question