如何将符号数组与矩阵随机相乘

时间:2019-12-06 20:49:25

标签: matlab

假设已知一个尺寸为n-by-n的矩阵W,其元素为01之间的正数。 还要假设一个符号向量

k = [a b c d];

我需要将W的所有非零分量与k的所有分量随机地相乘一次(随机),例如:

this one for example

我尝试过的事情:

k = sym('a', [1 4]);
msize = numel(k);
k(randperm(msize, 1))

for i = 1:length(W)
    for j = 1:length(W)
        W(i,j) = W(i,j)*(k);
    end
end

,错误如下:

The following error occurred converting from sym to double:
Error using maplemex
Error, (in MTM:-double) cannot handle unevaluated name `a1` in evalhf

1 个答案:

答案 0 :(得分:0)

首先,我们定义输入:

% PARAMETERS

% k: symbolic vector of length m
m = 4;
k = sym('a', [1, m]);

% W: n-by-n matrix of doubles
n = 5;
W = rand(n);

这里是计算:

% CALCULATION

% random assignment of elements of k to the shape of W
I = randi(m, n);
K = k(I);

% result: element-wise multiplication of K and W
result = K .* W;