2015-02-05 58 views
1

我有一個單元格數組,每列都有一個yx1單元格。我想隨機化列中的「行」。也就是說,對於元素爲a_1,a_2,... a_y的每個yx1單元,我想對a_i的索引應用相同的置換。如何在單元格陣列中重排行

我有做這個的功能,

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; 

但你可以看到這是一個有點難看。有沒有更自然的方式來做到這一點?

我意識到我可能使用了錯誤的數據類型,但由於遺留原因,我想避免切換。但是,如果答案是「切換」,那麼我想這就是答案。

回答

3

我假設你有列向量的單元陣列,如

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

在這種情況下,可以做這種方式:

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

或轉化到中間矩陣然後回到單元陣列:

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 
+0

很好用!我應該真的瞭解更多關於matlab中可用的高階編程。 – Nathan 2015-02-05 16:22:34

+1

[This](http://es.mathworks.com/help/matlab/matlab_prog/vectorization.html)可能是一個好開始 – 2015-02-05 16:47:45

相關問題