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.

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by