Replace certain elements in an array

3 ビュー (過去 30 日間)
MK96
MK96 2017 年 2 月 11 日
コメント済み: MK96 2017 年 2 月 11 日
The following code generates a 100x1 array of random 1s and -1s:
N = 100;
States = 2*randi(2,N,1) - 3;
Once generated, is there an easy way I can change some of the -1s to 1s whilst keeping the other elements the same?
e.g. for a 4x1 example if I had [1; -1; -1; -1] and wanted to change any 2 of the -1 elements to 1s: [1; -1; 1; 1], how could I do this?

採用された回答

Image Analyst
Image Analyst 2017 年 2 月 11 日
Try this:
N = 10; % Number of elements.
States = 2*randi(2,N,1) - 3
% Get the minus 1 element indexes
minusOneIndexes = find(States == -1)
% Get two random indexes:
indexes = randperm(length(minusOneIndexes), 2);
% Set them to +1
indexesToChange = minusOneIndexes(indexes)
States(indexesToChange) = 1
  1 件のコメント
MK96
MK96 2017 年 2 月 11 日
Thanks this worked

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by