簡體   English   中英

Matlab,單元格數組,邏輯數組索引和數組類型轉換

[英]matlab, cell arrays, logical array indexing, and array type conversion

我得到了一些未公開的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)

關於y=~isnan(x) ,您是對的。

帶有x(k,y(k,:))行將給出xk行中的not-Nans。 因此,似乎z正在收集x的not-Nans值(以一種奇怪的方式)。 注意y(k,:)充當列的邏輯索引,其中true表示“包括該列”,而false表示“不包括”。

至於您的最后一個問題: [z{:,:}]在此情況下等效於[z{:}] ,因為z僅具有一維,它將水平連接單元格數組z的內容。 例如, z{1} = [1; 2]; z{2} = [3 4; 5 6]; z{1} = [1; 2]; z{2} = [3 4; 5 6]; 它會給[1 3 4; 2 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{1} = [1 2]; z{2} = [3 4; 5 6]; 然后[z{:}][z{:,:}]給出錯誤。

因此,最終結果d只是行向量,其中包含x的非南斯(按順序遞增,然后遞增列排序)。 這本來可以更容易地獲得

xt = x.';
d = xt(~isnan(xt(:))).';

它更緊湊,更像Matlab,並且可能更快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM