2011-01-25 172 views
1

new_img是==>MATLAB:如何解決下標賦值維度不匹配問題?

new_img = zeros(height, width, 3); 

curMean是這樣的:[double, double, double]

new_img(rows,cols,:) = curMean; 

所以這裏有什麼問題?

+0

假設行列數在循環內部,並且賦值給curMean並賦值給curMean,然後應該沒有錯誤,curMean被分配給z/j(無論你想調用它)是多維數組的一部分。 – phwd 2011-01-25 17:31:27

+0

行和列是每個索引列表。 = \ – NullVoxPopuli 2011-01-25 17:33:36

回答

3

行:

new_img(rows,cols,:) = curMean; 

如果rowscols是標值纔有效。如果它們是矢量,那麼根據您正在進行的分配的具體情況,您需要執行一些選項才能正確執行分配。由於Jonas mentions in his answer,您可以爲rowscols中的每個成對索引組合分配值,也可以爲每對[rows(i),cols(i)]分配值。對於你在哪裏,每兩兩組合分配值的情況下,這裏有一對夫婦的方法可以做到這一點:

  • 分配分解成3個步驟,一個是在第三維度中的每個平面:

    new_img(rows,cols,1) = curMean(1); %# Assignment for the first plane 
    new_img(rows,cols,2) = curMean(2); %# Assignment for the second plane 
    new_img(rows,cols,3) = curMean(3); %# Assignment for the third plane 
    

    你也可以做到這一點的for循環Jonas suggested,但對於這麼小的迭代次數我還挺喜歡用一個「展開的」版本像上面。

  • 使用上curMean功能RESHAPEREPMAT重塑和複製載體中,使得它的new_img子索引截面的尺寸相匹配:

    nRows = numel(rows); %# The number of indices in rows 
    nCols = numel(cols); %# The number of indices in cols 
    new_img(rows,cols,:) = repmat(reshape(curMean,[1 1 3]),[nRows nCols]); 
    

有關如何的一個例子上面的作品,讓我們說我有以下幾點:

new_img = zeros(3,3,3); 
rows = [1 2]; 
cols = [1 2]; 
curMean = [1 2 3]; 

無論是abov e解決方案會給你這個結果:

>> new_img 

new_img(:,:,1) = 

    1  1  0 
    1  1  0 
    0  0  0 

new_img(:,:,2) = 

    2  2  0 
    2  2  0 
    0  0  0 

new_img(:,:,3) = 

    3  3  0 
    3  3  0 
    0  0  0 
2

要小心這樣的任務!

a=zeros(3); 
a([1 3],[1 3]) = 1 
a = 
    1  0  1 
    0  0  0 
    1  0  1 

換句話說,您分配所有行和列索引的組合。如果這是你想要的東西,寫

for z = 1:3 
    newImg(rows,cols,z) = curMean(z); 
end 

應該得到你想要的東西(如@gnovice建議)。

然而,如果rowscols匹配對(即你只要分配1到元件(1,1)(3,3)在上面的例子中),則可能會更好寫入

for i=1:length(rows) 
    newImg(rows(i),cols(i),:) = curMean; 
end 
相關問題