2012-07-26 53 views
-1

一種可能的解決方案如下。請注意,我自由地爲變量指定了有意義的名稱,因爲名稱如AStart Time A(它甚至不是有效的Matlab標識符)很容易混淆。你也可以看到你的矩陣 CStart Time C是多餘的,因爲所有的信息已經編碼在A, BStart Time A如何通過考慮speciall另一個矩陣輸入值到矩陣

% The values to put in the result matrix. 
value = [5 6 7; 
     7 5 6]; 
% Column index where each sequence starts in the result matrix. 
start = [2 3 7; 
     1 6 8]; 
% The length of each sequence, i.e. how often to put the value into the result. 
count = [1 2 3; 
     3 1 2]; 

% Determine the longest row. Note: At this place you could also check, if all 
% rows are of the same length. The current implementation pads shorter rows with 
% zeros. 
max_row_length = max(start(:, end) + count(:, end) - 1); 

% Allocate an output matrix filled with zeros. This avoids inserting sequences 
% of zeros afterwards. 
result = zeros(size(start, 1), max_row_length); 

% Finally fill the matrix using a double loop. 
for row = 1 : size(start, 1) 
    for column = 1 : size(start, 2) 
     s = start(row, column); 
     c = count(row, column); 
     v = value(row, column); 
     result(row, s : s + c - 1) = v; 
    end 
end 

result

result = 

    0  5  6  6  0  0  7  7  7 
    7  7  7  0  0  5  0  6  6 

的要求。

如何修改上述解決3D矩陣的代碼。

例如:第三個維度的尺寸爲2 矩陣值

value(:,:,1) = [5 6 7; 
       7 5 6]; 
value(:,:,2) = [6 5 7; 
       6 7 5]; 

start(:,:,1) = [2 3 7; 
       1 6 8]; 
start(:,:,2) = [1 5 6; 
       2 5 9]; 

count(:,:,1) = [1 2 3; 
       3 1 2]; 
count(:,:,2) = [2 1 3; 
       2 3 1]; 

我希望我的結果矩陣是

result(:,:,1) =[0 5 6 6 0 0 7 7 7; 
       7 7 7 0 0 5 0 6 6] 
result(:,:,2) =[6 6 0 0 5 7 7 7 0; 
       0 6 6 0 7 7 7 0 5] 

如何使代碼以使結果。謝謝

+0

您能否舉一個例子說明如何使用「深度」信息將元素放置到3D矩陣中?這裏用2D很簡單。我主要想知道如何提供信息以知道將元素放置在3D中的位置以及結果的例子。我認爲這可能就像添加另一個循環遍歷你的第三維一樣簡單。 – 2012-07-26 14:03:19

+0

@BenA。例如: – 2012-07-26 14:21:58

+0

@BenA。先生看到我更新的問題。我舉例說,第三維的大小是2.但實際上我有超過2. – 2012-07-26 14:37:16

回答

0

這應該給你一個如何解決這個問題的想法,如果它沒有完全回答它。我還沒有測試過我在這裏提供的代碼,只是簡單地修改你所提供的內容,盡我所知。

result = zeros(size(start, 1), max_row_length, size(start,3)); 

% Finally fill the matrix using a double loop. 
for depth = 1:size(start,3) 
    for row = 1 : size(start, 1) 
     for column = 1 : size(start, 2) 
      s = start(row, column, depth); 
      c = count(row, column, depth); 
      v = value(row, column, depth); 
      result(row, s : s + c - 1, depth) = v; 
     end 
    end 
end 
+0

@ Ben.A:謝謝你的代碼。你真的幫我先生。謝謝 – 2012-07-26 15:12:23