フィルターのクリア

How to assign few of the array values with a constant randomly .

5 ビュー (過去 30 日間)
chandra Naik
chandra Naik 2019 年 7 月 23 日
回答済み: chandra Naik 2019 年 7 月 24 日
I try with randperm but not getting an idea.
suppose n=10 and m=4;
require array with value '1' in 4 random position from 1 to 10 and othe postions value '0;
Expected result,
i.e array =[1, 0, 0, 1, 0, 0, 0, 0, 1,1] here m=4 and n=10
  1 件のコメント
madhan ravi
madhan ravi 2019 年 7 月 23 日
"I try with randperm but not geeting idea.„
Why?

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

採用された回答

Stephen23
Stephen23 2019 年 7 月 23 日
編集済み: Stephen23 2019 年 7 月 23 日
"How to assign few of the array values with a constant randomly ."
>> n = 10;
>> m = 4;
>> V = zeros(1,n); % generate array
>> X = randperm(n); % random indices
>> V(X(1:m)) = 1 % assign constant to some elements
V =
0 0 1 0 1 0 0 1 1 0
  2 件のコメント
chandra Naik
chandra Naik 2019 年 7 月 23 日
Thank you, it works as i expected.
chandra Naik
chandra Naik 2019 年 7 月 24 日
編集済み: chandra Naik 2019 年 7 月 24 日
Dear Stephen Cobeldick,
With continution with previous question,
Require array with value '1' in 4 random position from 1 to 10 and othe postions value '0;
Expected result,
i.e array =[1, 0, 0, 1, 0, 0, 0, 0, 1,1] here m=4 and n=10
Suppose two array values associated with m , say Xm and Ym (a point on a plane)
i.e Xm=[20,25,30,25] %X axis coordinate
Ym=[18,23,30,25] %Y axis coordinate,
then how to get corresponding array values Xm and Ym with respect to
[1, 0, 0, 1, 0, 0, 0, 0, 1,1]
i.e Xm_new=[20, 0, 0, 25, 0, 0, 0, 0, 30,25]
Ym_new=[18, 0, 0, 23, 0, 0, 0, 0, 30,25]
I trying with loops, if better approach could you share your thought.
Thank you

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

その他の回答 (2 件)

KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 7 月 23 日
編集済み: KALYAN ACHARJYA 2019 年 7 月 23 日
m=4;n=6;
A=[ones(1,m) zeros(1,n)];
[rows colm]=size(A);
colm_data=randperm(colm);
result=A(:,colm_data)
Please do change according as per your requirements (Minor Change)

chandra Naik
chandra Naik 2019 年 7 月 24 日
Problem resolved using soution of Stephen Cobeldick,
valuesX=zeros(1,n);
valuesY=zeros(1,n);
values = zeros(1,n); % generate array
X = randperm(n); % random indices
values(X(1:m)) = 1 % assign constant to some elements
disp(X);
valuesX(X(1:m))=Xm % assign Xm values
valuesY(X(1:m))=Ym % assign Ym values

カテゴリ

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