Daniel Safai
Daniel Safai

Reputation: 45

Store matrix from a loop in Matlab

I have a 5 by 3 matrix, e.g the following:

A=[1 1 1; 2 2 2; 3 3 3; 4 4 4; 5 5 5]

I run a for loop:

for i = 1:5
    AA = A(i)'*A(i);
end

My question is how to store each of the 5 (3 by 3) AA matrices?

Thanks.

Upvotes: 0

Views: 1316

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112759

Assuming, as in Geoff's answer, that you mean A(i,:)'*A(i,:) (to get 5 matrices of size 3x3 in your example), you can do it in one line with bsxfun and permute:

AA = bsxfun(@times, permute(A, [3 2 1]), permute(A, [2 3 1]));

(I'm also assuming that your matrices only contain real numbers, as in your example. If by ' you really mean conjugate transpose, you need to add a conj in the above).

Upvotes: 0

Geoff
Geoff

Reputation: 1603

You could pre-allocate enough memory to the AA matrix to hold all the results:

[r,c] = size(A);   % get the rows and columns of A (r and c respectively)
AA = zeros(c,c,r); % pre-allocate memory to AA for all 5 products 
                   % (so we have 5 3x3 arrays)

Now do almost the same loop as above BUT realize that A(i) in the above code only returns one element whereas you want the full row. So you want the data from row i but all columns which can be represented as 1:3 or just the colon :

for i=1:r
    AA(:,:,i) = A(i,:)' * A(i,:);
end

In the above, A(i,:) is the ith row of A and we are setting all rows and columns in the third dimension (i) of AA to the result of the product.

Upvotes: 1

Related Questions