Randomise the upper triangle of a matrix
显示 更早的评论
How can I randomise the elements only in the upper triangle of a square matrix? I want to randomise only the upper triangle elements 10,000 times, each time the upper triangle is different. Please suggest a solution.
Many thanks
Kyle
采纳的回答
更多回答(2 个)
Guillaume
2014-8-21
a(logical(triu(ones(size(a))))) = rand(1, sum(sum(triu(ones(size(a))))));
The sum(sum expression is just to find how many random numbers to generate.
Try the triu function that extracts the upper triangular part of a matrix.
b = ones(10);
a = randn(10);
aUpper = triu(a);
b(aUpper ~= 0) = aUpper(aUpper~=0); % To replace the upper elements in b.
Another solution is:
b = ones(10);
bL = tril(b);
a = randn(10);
aU = triu(a);
c = bL+aU;
I think I would do it as in the first example, but if you want you can try both and select the one you want. Of course you will need to create some kind of loop and do some stuff to save the matrices (or may use them and discard them, or whatever you need). However, from here you should be able to handle it by yourself.
Good luck!
类别
在 帮助中心 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!