How to randomly change element of matrix?

13 ビュー (過去 30 日間)
Ammy
Ammy 2021 年 9 月 14 日
コメント済み: Ammy 2021 年 9 月 14 日
I have an n×n matrix.
I want to randomly change the element of A at random position.
The element of matrix can be from 0 to 1000
I used randi(1000) for random entry
I want to repeat this process 100 times to get 100 new matrices and save all these matrices in a separate folder
for i= 1:I00

採用された回答

the cyclist
the cyclist 2021 年 9 月 14 日
I'll illustrate for an nxn where n = 3, and repeat 2 times:
% Set the random number generator seed, for repeatability here
rng default
% Size of matrix
n = 3;
% Starting matrix -- use your real data instead
M = magic(n);
% Loop two times
for ii = 1:2
% Chose random element index (using linear index)
rndIdx = randi(n*n);
% Change the random element to a random value from 1:1000 (which I guess is what you want?)
M(rndIdx) = randi(1000)
% Put save step here, if you want to save each one
end
M = 3×3
8 1 6 3 5 906 4 9 2
M = 3×3
8 1 6 914 5 906 4 9 2
This code keep going forward from the original matrix, changing elements one at a time (but sometimes it could overwrite the same location more than once). You'll need to adjust the code if you want to start from M, save, start from original M again, etc.
But hopefully you get the idea.
  3 件のコメント
the cyclist
the cyclist 2021 年 9 月 14 日
% Set the random number generator seed, for repeatability here
rng default
% Size of matrix
n = 3;
% Starting matrix -- use your real data instead
M = magic(n);
% Loop two times
for ii = 1:2
% Chose random element index (using linear index)
rndIdx = randi(n*n);
% Change the random element to a random value from 1:1000 (which I guess is what you want?)
Mnew = M;
Mnew(rndIdx) = randi(1000)
% Put save step here, if you want to save each one
end
Mnew = 3×3
8 1 6 3 5 906 4 9 2
Mnew = 3×3
8 1 6 914 5 7 4 9 2
Ammy
Ammy 2021 年 9 月 14 日
Thank you very much.

サインインしてコメントする。

その他の回答 (1 件)

Fabio Freschi
Fabio Freschi 2021 年 9 月 14 日
You can use linear indexing
% your matrix
A = rand(10,100);
% create the folder
mkdir('storage');
% loop
for i = 1:100
% random matrix
Arand(randi(numel(A))) = rand;
% save
save(strcat('./storage/mymatrix',num2str(i),'.mat'));
end
  2 件のコメント
Jan
Jan 2021 年 9 月 14 日
Or randi(1000) instead if rand().
Ammy
Ammy 2021 年 9 月 14 日
Thank you very much.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by