在矩阵内随机输入点

时间:2012-01-05 17:39:10

标签: matlab random

我想知道如何在matlab中给定指定(已给出尺寸)矩阵内随机输入点。

想到这样做,但我不确定 算法:

1)首先使用rand func生成指定维度的矩阵。

l=input('enter the length:');
b=input('enter the bth:');
g=rand(b,l)

2)然后使用循环检查维度。

3)取一些存储在p中的随机数并将其输入矩阵

1 个答案:

答案 0 :(得分:3)

你的问题有点不清楚。从我收集到的,你想要创建一些维度的随机矩阵,然后在矩阵中的随机位置插入存储在向量p中的一些数字。希望您可以使用下面给出的一些(或所有)代码来实现这一点。如您所见,不需要循环,它会自动处理不在同一位置插入两个数字。

%#Specify matrix dimensions
rows = 5;
cols = 8;

%#Create random matrix with values in (0,1)
M = rand(rows,cols);

%#Spesify parameters for numbers to insert and create p-vector
numbers_to_insert = 5;
number_range = [2 10];
p = randint(numbers_to_insert,1,number_range);

%#Select random locations to insert elements in p
rV = randperm(rows);
cV = randperm(cols);

%#Insert numbers into matrix by using 1 dimensional indexing
M(rV(1:numbers_to_insert)+(cV(1:numbers_to_insert)-1)*rows) = p; 

示例结果:

p =      5     5     8     9     3
rV=      1     3     4     5     2    
cV=      4     3     7     5     8     2     1     6 %#Only first 5 values used
M=
0.1656    0.7482    0.1524    5.0000    0.8173    0.8001    0.1455    0.1450
0.6020    0.4505    0.8258    0.1067    0.8687    0.4314    0.1361    3.0000
0.2630    0.0838    5.0000    0.9619    0.0844    0.9106    0.8693    0.6221
0.6541    0.2290    0.9961    0.0046    0.3998    0.1818    8.0000    0.3510
0.6892    0.9133    0.0782    0.7749    9.0000    0.2638    0.5499    0.5132