randomly change signs of certain elements in a matrix
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
mac-nic ifegbo
el 25 de Nov. de 2018
Comentada: mac-nic ifegbo
el 25 de Nov. de 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 comentarios
Respuesta aceptada
Stephen23
el 25 de Nov. de 2018
Editada: Stephen23
el 25 de Nov. de 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)
Más respuestas (0)
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!