如何在matlab中为每个矩阵元素添加一个随机数?

时间:2020-11-29 13:41:38

I have the following matrix X and Column vector H:

我有以下矩阵X和列向量H:

 X=[ 1 2 3; 2 3 4; 3 4 5];
 H=[1; 2 ;3];
 m=[X(:,1) H(:) X(:,2) H(:) X(:,3) H(:)];

How do i add a small random number to all elements of m while keeping every column H in the matrix m the same after adding the random number?

如何在添加随机数后将矩阵中的每列H保持相同的同时为m的所有元素添加一个小的随机数?

2 个解决方案

#1


2  

You should add the random numbers separately, and then build your combined matrix.

您应该单独添加随机数,然后构建组合矩阵。

Xnew = X + rand(size(X)); % replace 'rand' with the random numbers you want
Hnew = H + rand(size(H));
mnew = [Xnew(:,1) Hnew(:) Xnew(:,2) Hnew(:) Xnew(:,3) Hnew(:)];

#2


0  

you can add the random to X instead of m

你可以将随机数添加到X而不是m

rX = X + rand(size(X)); % add uniformly distributed random numbers in [0,1] interval
m=[rX(:,1) H(:) rX(:,2) H(:) rX(:,3) H(:)];

#1


2  

You should add the random numbers separately, and then build your combined matrix.

您应该单独添加随机数,然后构建组合矩阵。

Xnew = X + rand(size(X)); % replace 'rand' with the random numbers you want
Hnew = H + rand(size(H));
mnew = [Xnew(:,1) Hnew(:) Xnew(:,2) Hnew(:) Xnew(:,3) Hnew(:)];

#2


0  

you can add the random to X instead of m

你可以将随机数添加到X而不是m

rX = X + rand(size(X)); % add uniformly distributed random numbers in [0,1] interval
m=[rX(:,1) H(:) rX(:,2) H(:) rX(:,3) H(:)];