【问题标题】:accessing nth column of a cell array in matlab在matlab中访问单元格数组的第n列
【发布时间】:2018-12-06 15:21:53
【问题描述】:

我有一个单元格数组,例如 3 个单元格,其中单元格是 (3,8)、(3,2)、(3, 30) 矩阵,现在我想在不转换的情况下访问整个数据的第 n 列我的单元格到矩阵,例如,如果我搜索第 8 列,它必须是第 3 个单元格的第二列。一种方法是将其转换为矩阵,但我的单元格太长,当我尝试将整个单元格转换为矩阵时,它会让我内存不足。然后我尝试了下面的代码,但它不能正常工作。我想知道我做错了什么。

感谢任何帮助。

function [col,i,idx] = find_cellCol(cel, idx)
lgh = length(cel);
i = 1;

me = zeros(2,length(cel));
while( i <= lgh && length(cel{1,i})<=idx)

idx = idx - length(cel{1,i});
i = i+1;

end%end while

if idx == 0
col = cel{1,i-1}(:,end);
else
col = cel{1,i}(:,idx);
end
end

【问题讨论】:

  • length(x)max(size(x)) 相同。您想使用size(x,2) 来获取数组中的列数。

标签: matlab out-of-memory cell cell-array


【解决方案1】:

仅获取每个单元格的每个矩阵的行数,然后将这些行数相加并检查到达第 8 行的单元格。

%dummy data
x{1} = rand(3,8);
x{2} = rand(3,2);
x{3} = rand(3,20);

val   = 8;
csize = cellfun(@(x) size(x,1),x);    %get the number of line for each cell
csum  = cumsum(csize);                % [3,6,9]
ind   = find(csum>=val,1);            % on which cell do we reach the # line
x{ind}((val-csum(ind))+csize(ind),:)  %access the right line

fprintf('Accessing the line %d of the cell %d',(val-csum(ind))+csize(ind),ind)

哪个会返回:

Accessing the line 2 of the cell 3

编辑:

给定的示例误导了我,因为我确定您正在尝试访问一行(第一维)而不是列(第二维)。

但是如果你想访问一个列,你可以简单地调整上面的代码:

val   = 8;
csize = cellfun(@(x) size(x,2),x);    %get the size of the second dimension now.
csum  = cumsum(csize);                
ind   = find(csum>=val,1);            
x{ind}(:,(val-csum(ind))+csize(ind))  %access the right column

【讨论】:

  • 很好,除了 OP 想要获得 columns,而不是行。这意味着您应该使用size(x,2) 而不是size(x,1),并在稍后修复索引。
  • 非常感谢,伙计们 – CrisLuengo, – obchardon。但是当我试图找到第一列时,它给了我:访问单元格的第 1 列 -7访问单元格 2 的第 1 列;而且“ind”也有两个值!
  • @AZiZASaber 看起来您已经修改了上面的代码。使用find(condition,1),其中1 表示find 必须只返回第一次出现。
猜你喜欢
  • 1970-01-01
  • 2015-04-27
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 2016-09-30
相关资源
最近更新 更多