MATLAB多个单元格 - 操作(交换并转换为数组)

时间:2017-02-08 15:29:13

标签: matlab cell sparse-matrix

val表示值,col_ind是矩阵中的值列索引 假设我们想要将这两个数组作为结果:

  val=     [9 -2 9 -2 -2 9 -2]
  col_ind= [1  2 2  1  3 3  2]

来自2个单元{val}和{col_ind}

  {val}    = [9;-2] [-2;9;-2] [-2;9]
  {col_ind}= [1,2] [0,0,1,2,3] [0,0,0,0,0,2,3]

如何摆脱{col_ind}中双打中的零来获取此

  

{col_ind} = [1,2] [1,2,3] [2,3]

如何交换每个双重中的条目并确保 列索引被适当地交换,以便我得到这个:

  {val}    = [9;-2] [9;-2;-2] [9;-2]
  {col_ind}= [1,2]  [2,1,3]   [3,2]

在这种情况下如何使用函数排序?

如何将单元格合并在一起最终得到这个数组:

  col_ind = [1 2 2 1 3 3 2]

2 个答案:

答案 0 :(得分:0)

希望我理解正确:

col_ind= {[1,2], [0,0,1,2,3], [0,0,0,0,0,2,3]}; %define col_ind - note row vector
val    = {[9;-2]; [-2;9;-2]; [-2;9]}; %define val - note column vectors

for cellNum=1:length(col_ind) %loop for each cell inputted
    [val_sorted{cellNum},sortMap]=sort(val{cellNum},'descend'); %Sort val in descending order - not exactly clear from your Q!
    colInd_noZeros=col_ind{cellNum}(col_ind{cellNum}~=0); %Remove zeros from this col_ind cell (your 1st Q?)
    colInd_sorted{cellNum}=colInd_noZeros(sortMap); %re-order col_ind to match sorted val (your 2nd Q?)
end
%Now combine cells into an array, direction depends, use "vertcat" for column arrays, and "[]" for the row arrays (your 3rd Q?)
valArray=vertcat(val_sorted{:})'
col_indArray=[colInd_sorted{:}]

答案 1 :(得分:0)

以下是使用sortrowscellfun而不是for loop执行此操作的可能方法。

col_ind = {[1,2],[0,0,1,2,3],[0,0,0,0,0,2,3]}
val = {[9;-2], [-2;9;-2], [-2;9]}

col_ind = cellfun(@(x)x(x~=0),col_ind,'uni',0) % Get rid of zeros from the indices
 % Sort in descending order and split results in cells
valAndIdx = cellfun(@(x,y)mat2cell(sortrows([x y(:)],-1),numel(x),[1 1]),val,col_ind,'uni',0)

tmp = (valAndIdx{:})
valArray = tmp(:,1)
col_indArray = tmp(:,2)