如何随机排列单元格数组中的行 [英] How to shuffle the rows in a cell array

查看:86
本文介绍了如何随机排列单元格数组中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有x列的单元格数组,每列都有一个yx1单元格.我想随机化列中的行".也就是说,对于每个具有元素a_1,a_2,... a_y的yx1单元,我想对a_i的索引应用相同的置换.

I have a cell array with x columns, each with a yx1 cell. I would like to randomize the "rows" within the columns. That is, for each yx1 cell with elements a_1, a_2, ... a_y, I would like to apply the same permutation to the indices of a_i.

我有一个执行此操作的功能,

I've got a function that does this,

function[Oarray] = shuffleCellArray(Iarray);

    len   = length(Iarray{1});
    width = length(Iarray);
    perm  = randperm(len);

    Oarray=cell(width, 0);

    for i=1:width;
        for j=1:len;
            Oarray{i}{j}=Iarray{i}{perm(j)};
        end;
    end;

但是如您所见,它有点难看.有更自然的方法吗?

but as you can see it's a bit ugly. Is there a more natural way to do this?

我意识到我可能使用了错误的数据类型,但是出于遗留原因,我想避免切换.但是,如果答案是切换",那么我想这就是答案.

I realize that I'm probably using the wrong data type, but for legacy reasons I'd like to avoid switching. But, if the answer is "switch" then I guess that's the answer.

推荐答案

我假设您有一个列向量的单元格数组,例如

I'm assuming you have a cell array of column vectors, such as

Iarray = {(1:5).' (10:10:50).' (100:100:500).'};

在这种情况下,您可以这样操作:

In that case, you could do it this way:

ind = randperm(numel(Iarray{1})); %// random permutation
Oarray = cellfun(@(x) x(ind), Iarray, 'UniformOutput', 0); %// apply that permutation
                                                           %//  to each "column"

或转换为中间矩阵,然后返回至单元格数组:

Or converting to an intermediate matrix and then back to a cell array:

ind = randperm(numel(Iarray{1})); %// random permutation
x = cat(2,Iarray{:}); %// convert to matrix
Oarray = mat2cell(x(ind,:), size(x,1), ones(1,size(x,2))); %// apply permutation to rows
                                                           %// and convert back

这篇关于如何随机排列单元格数组中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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