2013-10-04 97 views
0

我已經給出了一些未公開的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) 

回答

3

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

該行與x(k,y(k,:))將給x的第k行中的非Nans。所以看起來z正在收集非Nans值x(以一種奇怪的方式)。請注意,y(k,:)充當列的邏輯索引,其中true表示「包含該列」,而false表示「不包含」。

至於你的最後一個問題:[z{:,:}]在這種情況下相當於[z{:}],因爲z只有一個維度,它會水平拼接單元陣列z的內容。例如,與z{1} = [1; 2]; z{2} = [3 4; 5 6];它會給[1 3 4; 2 5 6]。因此m將是共同構成zn矩陣中的行數(在我的示例中m將2和n將3)的總和。如果沒有這種常見的行數,它會給出錯誤。例如,如果z{1} = [1 2]; z{2} = [3 4; 5 6];然後[z{:}][z{:,:}]給出錯誤。

所以最終結果d只是一個行向量,它包含了從增加行然後增加列排序的x中的非Nans。這可能更容易獲得,因爲它更緊湊,更像Matlab,可能更快。

+0

啊,我用x(k,(k :))輸入了一行錯誤。它應該是x(k,z(k :))。我在代碼中糾正了這一點。水平連接和邏輯數組索引(在我修正的行中)是有道理的,可以選擇並連接非NaN數字,但我仍然不確定數組z的大小/維數將保持不變(即,什麼大小/維數組是通過由邏輯數組索引來創建的)。另外我想你倒過了n的意思& m;注意這條線是[m,n] = size(d),而不是[n,m] = size(d)。 – composerMike

+0

你對m和n是正確的。通過你的修正,代碼更有意義。請參閱最新的答案。 –

+1

代碼以奇怪的方式獲得結果('d')。這不是在Matlab中做事情的標準方式。在這裏可以很容易地避免循環,單元陣列絕對不是必需的,爲什麼按行處理?我可以問你從哪裏得到?某種自動生成或翻譯的代碼? –