Change 1 to -1 in a matrix

2 ビュー (過去 30 日間)
Offroad Jeep
Offroad Jeep 2016 年 9 月 26 日
コメント済み: KSSV 2016 年 9 月 26 日
Hi to all the members, I have a 4 X 4 Matrix of one i.e ones(4). I want to change all the elements from 1 to -1 randomly in the matrix. BUT Only one element should change at a time from 1 to -1. That it the 1 changes to -1 sixteen times as we have sixteen elements in the matrix.

採用された回答

Adam
Adam 2016 年 9 月 26 日
m = ones(4);
r = rand(4) - 0.5;
m = m .* sign( r );
is one of many ways to do it.
  2 件のコメント
Offroad Jeep
Offroad Jeep 2016 年 9 月 26 日
Thanks for reply......Kindly see the question as i left some idea what i needed
Adam
Adam 2016 年 9 月 26 日
orderIdx = randperm(16);
for n = 1:16
m( orderIdx(n) ) = -1;
end

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

その他の回答 (1 件)

KSSV
KSSV 2016 年 9 月 26 日
編集済み: KSSV 2016 年 9 月 26 日
A = ones(4,4) ;
N = 5 ; % number of ones to make negative
idx = randsample(1:16,N) ; % select N random positions to change 1 to -1
A(idx) = -1 ;
  4 件のコメント
Offroad Jeep
Offroad Jeep 2016 年 9 月 26 日
giving error as one 1 remains unchanged.... can please go through... regards
KSSV
KSSV 2016 年 9 月 26 日
At the end:
A(pos) = -1 ;

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by