How to define my own signum function

7 Ansichten (letzte 30 Tage)
Anthony
Anthony am 29 Jun. 2014
Kommentiert: Dhananjay Mehta am 22 Feb. 2021
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 Kommentar
mariam mansoor
mariam mansoor am 18 Jul. 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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Mischa Kim
Mischa Kim am 29 Jun. 2014
Bearbeitet: Mischa Kim am 29 Jun. 2014
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
  1 Kommentar
Dhananjay Mehta
Dhananjay Mehta am 22 Feb. 2021
And how can I get its graph x-y? I have tried using plot(x,y), but doesn't work..

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Star Strider
Star Strider am 29 Jun. 2014
You could do it one line with Anonymous Functions:
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.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by