How to define my own signum function
6 次查看(过去 30 天)
显示 更早的评论
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
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
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
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
2014-6-29
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.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!