randomly change signs of certain elements in a matrix

11 views (last 30 days)
Dear All,
I have a matrix of elements like this: a=[1 -1 1 ; 1 1 1 ; -1 -1 1] and i want to change the signs of say 3 or 4 elements of this matrix by random means so that the result could be a=[-1 -1 1 ; -1 -1 1 ; -1 1 1] or anything that changes the signs of 3 or 4 elements in the matrix.
Anyone with idea, please assist, am a beginner in matlab
Thanks

Accepted Answer

Stephen23
Stephen23 on 25 Nov 2018
Edited: Stephen23 on 25 Nov 2018
Do NOT use a loop for this! You can do this very simply with logical indexing:
>> a = [1,-1,1;1,1,1;-1,-1,1]
a =
1 -1 1
1 1 1
-1 -1 1
>> idx = randperm(numel(a),4);
>> a(idx) = -a(idx)
a =
-1 -1 1
1 1 1
1 1 -1
You can even randomly pick 3 or 4 elements:
idx = randperm(numel(a),randi([3,4]));
For versions prior to R2011b you will need to return the entire vector and select from that:
vec = randperm(numel(a));
idx = vec(1:4);
a(idx) = -a(idx)

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!