R[1;-1] how i write the program in matlab for random selection between 1 and -1
Show older comments
Accepted Answer
More Answers (2)
Torsten
on 2 Jan 2018
x = rand;
if x <= 0.5
number = 1;
else
number = -1;
end
Best wishes
Torsten.
Pawel Jastrzebski
on 2 Jan 2018
clear all;
clc;
% use 'random function' of your choice
% - rand()
% - randi()
% - randn()
% GENERATES A RANDOM NUMBER IN A RANGE OF -1 TO 1:
r1 = -1+ 2*rand(1);
% GETS THE SIGN OF THE 'r1'
sVal = sign(r1);
% ALL ABOVE CAN BE DONE IN ONE LINE:
sVal1 = sign(-1+ 2*rand(1));
2 Comments
Jan
on 2 Jan 2018
The sign() function can reply 0 also, if rand replies 0.5.
Pawel Jastrzebski
on 2 Jan 2018
Good point - thanks for correcting.
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!