How to code a multivalued sign function
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
lady bird
am 30 Mär. 2015
Kommentiert: lady bird
am 1 Apr. 2015
Hello all Please could you help me i want to code a multivalued signum function that is defined by
Let x ∈ R. The multivalued signum function Sgn: R ⇒ R is defined as:
sgn(x) ={ 1 if x > 0 −1 if x < 0 [−1, 1] if x = 0.
If x ∈ R^n then the multivalued signum function Sgn: R^n⇒R^n
is defined as: Sgn(x) : = (Sgn(x1), . . . , Sgn(xn))^T
Thank you so much for your help Best regards
0 Kommentare
Akzeptierte Antwort
Stephen23
am 1 Apr. 2015
Bearbeitet: Stephen23
am 1 Apr. 2015
Based on the explanation given "Can we program the same function but when x=0 the output sgn(0) is to take any value in the range [-1,1]?", then this fully vectorized code will achieve this:
function Y = msgn(X)
% Multivalued sign function
Y = sign(X);
Z = Y==0;
Y(Z) = 1-2*rand(1,sum(Z(:)));
end
And then we can test it:
>> msgn(5)
ans =
1
>> msgn(-5)
ans =
-1
>> msgn(0)
ans =
-0.6294
>> msgn([-5,0,0,0,5])
ans =
-1.0000 -0.8116 0.7460 -0.8268 1.0000
Weitere Antworten (1)
Stephen23
am 30 Mär. 2015
Bearbeitet: Stephen23
am 30 Mär. 2015
Two simple versions: the first assumes that the input is a scalar numeric:
function v = sgn(x)
assert(isscalar(x),'input must be scalar')
a = [-1,1];
v = a([x<=0,x>=0]);
end
>> sgn(-5)
ans = -1
>> sgn(0)
ans = [-1,1]
>> sgn(5)
ans = 1
The second allows a vector input:
function v = sgn(x)
assert(isvector(x),'input must be vector')
a = [-1;1];
u = arrayfun(@(n)a([n<=0,n>=0]),x(:),'UniformOutput',false);
v = reshape(cell2mat(u),1:isrow(x),1:iscolumn(x));
end
>> sgn([-5,0,5])
ans = -1 -1 1 1
0 Kommentare
Siehe auch
Kategorien
Mehr zu Parametric Spectral Estimation finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!