randomly change signs of certain elements in a matrix
11 views (last 30 days)
Show older comments
mac-nic ifegbo
on 25 Nov 2018
Commented: mac-nic ifegbo
on 25 Nov 2018
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
0 Comments
Accepted Answer
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)
See Also
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!