How to define my own signum function

조회 수: 6 (최근 30일)
Anthony
Anthony 2014년 6월 29일
댓글: Dhananjay Mehta 2021년 2월 22일
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
mariam mansoor
mariam mansoor 2020년 7월 18일
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

댓글을 달려면 로그인하십시오.

채택된 답변

Mischa Kim
Mischa Kim 2014년 6월 29일
편집: Mischa Kim 2014년 6월 29일
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
Dhananjay Mehta
Dhananjay Mehta 2021년 2월 22일
And how can I get its graph x-y? I have tried using plot(x,y), but doesn't work..

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Star Strider
Star Strider 2014년 6월 29일
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.

카테고리

Help CenterFile Exchange에서 Signal Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by