自动填充矩阵,无需重复行 [英] Auto-fill matrix without row-repetitions

查看:86
本文介绍了自动填充矩阵,无需重复行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列数字:

test = [1 1 1 2 2 2 3 3 3 4 4 4 5 5 5]

我想随机填充到3x5矩阵中,而在同一行中没有相同的数字.

which I want to randomely fill into a 3x5 matrix without having the same number in the same row.

如何在matlab中做到这一点?可能我可以将测试向量随机化,并将其填充到5x3矩阵中,但是我不知道如何在不获得相同行数的情况下执行此操作.

How can I do this in matlab? Potentially I could randomize the test vector and fill it into the 5x3 matrix but I don't know how to do this without getting the same number in the same row.

推荐答案

如果要使用test中的所有值填充3×5矩阵,请确保每一行都没有重复的值,则可以通过使用 toeplitz 来最简单地做到这一点矩阵,然后使用 randperm 随机置换尺寸:

If you want to fill a 3-by-5 matrix with all of the values in test, making sure each row has no repeated values, you can do this very succinctly by using toeplitz to first generate an index matrix, then randomly permute the dimensions with randperm:

index = toeplitz(1:3, [3 5:-1:2]);
index = index(randperm(3), randperm(5));

和示例index:

index =

     1     5     4     2     3
     4     3     2     5     1
     5     4     3     1     2

如果您在test中的值是数字1到5,这应该是您需要做的所有事情.如果test可以是具有5个不同数字的任何矢量,每个数字三个,那么您可以获取 test向量的唯一值,并用index对其进行索引.该解决方案将推广到任何test向量:

If your values in test are the numbers 1 through 5, this should be all you need to do. If test could be any vector with with 5 different numbers, three of each, then you can get the unique values of your test vector and index them with index. This solution will generalize to any test vector:

test = [3 3 3 7 7 7 5 5 5 9 9 9 4 4 4];    % Sample data
uniqueValues = unique(test);               % Get the unique values [3 4 5 7 9]
M = uniqueValues(index);                   % Use index as generated above

结果将保证是test中的内容的重新排序版本:

And the result will be guaranteed to be a reordered version of what's in test:

M =

     3     9     7     4     5
     7     5     4     9     3
     9     7     5     3     4

这篇关于自动填充矩阵,无需重复行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆