matlab,单元数组,逻辑数组索引和数组类型转换

时间:2013-10-04 20:39:20

标签: arrays matlab

我已经获得了一些未记录的Matlab代码,并试图找出它的作用。我'已经 把我的主要问题放在下面,作为代码中穿插的评论。

% x is an array, I believe of dimension (R, 2)
% I understand that the following line creates a logical array y of the same 
% dimensions as x in which every position that has a number (i.e. not Nan) 
% contains True.
y=~isnan(x)

for k=1:R
   % I don't know if z has been previously defined. Can't find it anywhere 
   % in the code I've been given. I understand that z is a cell array. The
   % logical array indexing of x, I understand basically looks at each row
   % of x and creates a 1-column array (I think) of numbers that are not Nan,
   % inserting this 1-column array in the kth position in the cell array z.
   z{k}=x(k, y(k,:))
end
% MAIN QUESTION HERE: I don't know what the following two lines do. what 
% will 'n' and 'm' end up as? (i.e. what dimensions are 'd'?) 
d=[z{:,:}]
[m,n]=size(d)

1 个答案:

答案 0 :(得分:3)

关于y=~isnan(x),你是对的。

x(k,y(k,:))行会在第kx中给出非Nans。所以z似乎正在收集x的非Nans值(以一种奇怪的方式)。请注意,y(k,:)充当列的逻辑索引,其中true表示“包含该列”,false表示“不包含”。

至于你的上一个问题:[z{:,:}]在这种情况下等同于[z{:}],因为z只有一个维度,它将水平连接单元格数组z的内容1}}。例如,对于z{1} = [1; 2]; z{2} = [3 4; 5 6];,它会提供[1 3 4; 2 5 6]。因此,m将是组成z的矩阵中的常用行数,而n将是列数的总和(在我的示例m将为2,n将为3)。如果没有这样的常见行数,则会产生错误。例如,如果z{1} = [1 2]; z{2} = [3 4; 5 6];,则[z{:}][z{:,:}]会出错。

因此,最终结果d只是一个行向量,其中包含来自x的not-Nans,通过增加行然后增加列来排序。

可以更容易地获得
xt = x.';
d = xt(~isnan(xt(:))).';

更紧凑,更像Matlab,可能更快。