How to make a matrix from four looping variables in MATLAB?

I want to create an F matrix with four components: F11, F12, F21, and F22

F11...F22 are variables being created from a for loop

that is,
for i=1:240
F11(i)=i + 1

and so on

Now, I want to create a separate matrix for each one of these four variables at each iteration of x

that is

F(1)=[F11(1),F12(1);F21(1),F22(1)]

all the way up to

F(240)=[F11(240),F12(240);F21(240),F22(240)]

I can't figure it out, i keep getting a single F matrix that sums all the values up, which is what i don't want. Help?

ooorah2014-11-10T06:13:13Z

Favorite Answer

I'm guessing you'll want a three-dimensional array, where each "layer" contains the matrix [F11 F12 ; F21 F22] for that time slot. Assuming you already have row vectors for F11, F12, etc, you could build this with a for loop:

F = zeros(2, 2, length(F11)); % Always remember to preallocate
for k = 1:length(F11)
F(:, :, k) = [F11(k) F12(k) ; F21(k) F22(k)];
end

Although it would be more efficient to just reshape your row vectors and put them in place:

shape = [1 1 length(F11)];
F = [reshape(F11, shape) reshape(F12, shape) ; reshape(F21, shape) reshape(F22, shape)];

And even more efficient to have just built the array F rather than building F11, ect first. Now you would access each layer in the third index F(:, :, 25) is [F11(25) F12(25) ; F21(25) F22(25)].

Or, maybe you want to use a cell array instead. That is less space efficient, but maybe is easier to look at?

F = cell(length(F11), 1); % Always remember to preallocate
for k = 1:length(F11)
F{k} = [F11(k) F12(k) ; F21(k) F22(k)];
end

And now you would access each layer with F{k}. Note the curly braces. That is important.