Mimi S.
Mimi S.

Reputation: 3

How to fill a 3D array in Matlab using nested for loops?

I am trying to fill a 3D array in Matlab using nested for loops. The inner for loop creates a matrix Xtemp of size 1920x16. The outer for loop should enter each of the 68 Xtemp matrices into a 3D array X.

Xtemp = [];  
X = [];
X = zeros(1920,16,68);
for j= 1:68
    for i= 1:16
        Xtemp = [Xtemp illum(:, i, j)];
    end
    X(:,:,j) = Xtemp;
end

I get the following error:

Subscripted assignment dimension mismatch.
Error in proj1_lda (line 25)
    X(:,:,j) = Xtemp;

If i remove the outer for loop, I am able to fill only the first matrix (j=1) into the 3D array, so I know the dimensions match and the syntax should be correct. But when I try to fill in all 68 matrices (or any more than 1), I get the error. Interestingly, even if I run the for loop more than once but I instead use X(:,:,1) = Xtemp;, this also gives the error. So it seems that the problem is directly related to running the outer for loop more than once.

I have spent a lot of time trying to figure this out and would appreciate any help.

Upvotes: 0

Views: 569

Answers (1)

Nimrod Morag
Nimrod Morag

Reputation: 984

After the first iteration you forgot to clear Xtemp.

So after you complete the inner loop the second time, Xtemp's "width" is 32.

You can move the line Xtemp = [] to the beginning of the outer loop.

Upvotes: 2

Related Questions