How to define my own signum function
Afficher commentaires plus anciens
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?
1 commentaire
mariam mansoor
le 18 Juil 2020
syms n
n=-20:0.01:20;
x_n1=heaviside(n);
subplot(4,1,1)
plot(n,x_n1)
title('unit step')
ylabel('u(n)')
xlabel('DISCRETE TIME')
axis([-10 10 -3 3])
x_n2= n<=0;
subplot(4,1,2)
plot(n,x_n2)
title('flipped unit step')
ylabel('u(-n)')
xlabel('DISCRETE TIME')
axis([-10 10 -3 3])
signum=x_n1 - x_n2;
subplot(4 ,1 ,3)
plot(n,signum)
title('SIGNUM FUNCTION')
ylabel('sign(n)')
xlabel('DISCRETE TIME')
axis([-10 10 -3 3])
grid on
heres the code to create a signum funtion using your own way....it creates two unitsteps and then sums the two to give a signum plot
Réponse acceptée
Plus de réponses (1)
Star Strider
le 29 Juin 2014
X = [-3 0 4];
sgn = @(x) fix((x)./abs(x+eps));
Y = sgn(X)
produces:
Y =
-1 0 1
The logic is fairly straightforward. It adds a very small number ( eps ) to the denominator to avoid Inf or NaN results for zero values in the array, does the division, and then rounds the integer value toward zero with the fix function to avoid fractions in the answer.
Catégories
En savoir plus sur Signal Operations dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!