Effacer les filtres
Effacer les filtres

How can I replace random elements of a matrix with some definite respective values in a single line command?

7 vues (au cours des 30 derniers jours)
I can replace a single element of a matrix. Or change multiple elements in an arithmetic series like 1st, 3rd, 5th element of a matrix with respective numbers. Or even a range of elements like 1st to 5th. But I want to randomly replace some elements with some numbers by one single line command. Like 1st, 2nd, 5th, 8th, 9th, 11th element of a matrix. Is it possible to do that with a single line code?
A=[1 2 3;4 5 6;7 8 9]
A(1)=10
A(2)=11
A(3)=12
Or
A(1:5)=[10, 11, 12, 13, 14]
A(1:2:5)=[10, 11, 12]
But don't know how to do the last thing I mentioned. Looking for help.
  2 commentaires
Dyuman Joshi
Dyuman Joshi le 23 Sep 2023
"But I want to randomly replace some elements with some numbers by one single line command. Is it possible to do that with a single line code?"
If I understand you correctly, it is -
A = magic(5)
A = 5×5
17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
A([1 8 13 22]) = [-4 -2 0 69]
A = 5×5
-4 24 1 8 15 23 5 7 14 69 4 -2 0 20 22 10 12 19 21 3 11 18 25 2 9

Connectez-vous pour commenter.

Réponses (2)

Star Strider
Star Strider le 23 Sep 2023
You are using ‘’inear indexing, and that will definitely work, although I am not certain what you want to do.
For a full explanation, see Matrix Indexing and the sub2ind and ind2sub functions to understand how they work and what they do.
A=[1 2 3;4 5 6;7 8 9]
A = 3×3
1 2 3 4 5 6 7 8 9
A(1)=10
A = 3×3
10 2 3 4 5 6 7 8 9
A(2)=11
A = 3×3
10 2 3 11 5 6 7 8 9
A(3)=12
A = 3×3
10 2 3 11 5 6 12 8 9
A=[1 2 3;4 5 6;7 8 9]
A = 3×3
1 2 3 4 5 6 7 8 9
A(1:6)=[10, 11, 12, 13, 14, 15]
A = 3×3
10 13 3 11 14 6 12 15 9
A=[1 2 3;4 5 6;7 8 9]
A = 3×3
1 2 3 4 5 6 7 8 9
A(1:2:5)=[10, 11, 12]
A = 3×3
10 2 3 4 12 6 11 8 9
.

Voss
Voss le 23 Sep 2023
Modifié(e) : Voss le 23 Sep 2023
"I want to randomly replace some elements with some numbers by one single line command"
A=[1 2 3;4 5 6;7 8 9];
n = 6; % number of elements to replace
idx = randperm(numel(A),n) % indices of elements to be replaced with new values
idx = 1×6
8 1 4 5 3 7
val = rand(1,n) % new values
val = 1×6
0.0840 0.0074 0.4788 0.8361 0.8203 0.0097
A(idx) = val % perform the replacement
A = 3×3
0.0074 0.4788 0.0097 4.0000 0.8361 0.0840 0.8203 8.0000 9.0000
A=[1 2 3;4 5 6;7 8 9];
% one-line version:
A(randperm(numel(A),6)) = rand(1,6);
  2 commentaires
Dyuman Joshi
Dyuman Joshi le 23 Sep 2023
Modify this
idx = randperm(numel(A));
idx = idx(1:n);
to -
idx = randperm(numel(A),n);
and eliminate subsref() and substruct()
A(randperm(numel(A),n)) = rand(1,6);

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by