开发者

MATLAB: How do I fix subscripted assignment dimension mismatch?

new_img is ==>

new_img = zeros(height, width, 3); 

curMean is like this: [double, double, double]

new_img(rows,cols,:) = curMean;

so what is wr开发者_如何学Cong here?


The line:

new_img(rows,cols,:) = curMean;

will only work if rows and cols are scalar values. If they are vectors, there are a few options you have to perform the assignment correctly depending on exactly what sort of assignment you are doing. As Jonas mentions in his answer, you can either assign values for every pairwise combination of indices in rows and cols, or you can assign values for each pair [rows(i),cols(i)]. For the case where you are assigning values for every pairwise combination, here are a couple of the ways you can do it:

  • Break up the assignment into 3 steps, one for each plane in the third dimension:

    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
    

    You could also do this in a for loop as Jonas suggested, but for such a small number of iterations I kinda like to use an "unrolled" version like above.

  • Use the functions RESHAPE and REPMAT on curMean to reshape and replicate the vector so that it matches the dimensions of the sub-indexed section of 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]);
    

For an example of how the above works, let's say I have the following:

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

Either of the above solutions will give you this result:

>> 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


Be careful with such assignments!

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

In other words, you assign all combinations of row and column indices. If that's what you want, writing

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

should get what you want (as @gnovice suggested).

However, if rows and cols are matched pairs (i.e. you'd only want to assign 1 to elements (1,1) and (3,3) in the above example), you may be better off writing

for i=1:length(rows)
    newImg(rows(i),cols(i),:) = curMean;
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜