MATLAB Answers

How to pre-allocate a matrix (from cell) when dimensions change

조회 수: 1(최근 30일)
Fede C 2018 London
Fede C 2018 London 2021년 7월 23일
댓글: Fede C 2018 London 2021년 7월 26일
Dear all,
B is a 1x3 cell. The 1st element is empty (it doesn't matter because my loop will start at position 2). the other elements are 218x2 and 266x2.
I have a loop that is meant to do 'stuff', resulting in a vector 'cofcoefvector' that is 2X13. What I'm doing is partly correct, partly because row 1 and row 2 have the same values (the values are correct for r=3). Somehow, I repeat the operation. I think that's because I over-write C (see below) in the loop, and that because I haven't indexed it. I haven't done so, because I'm not able to.
for r = 2: size(B,2);
C=cell2mat(B(r));
for m=1:size(A,2);
j=A(m);
tempmat1 = corrcoef(bpassf(C(:,2),6,32),lagmatrix(bpassf(C(:,1),6,32),j),'rows','complete');
for row=1:size(corcoefvector,1);
corcoefvector(row,m) = tempmat1(1,2); %this puts the same results in both rows. why?
end
end %this is the end of for t = etc, but it just creates 2 identical copies
end
I thought that was because I (think, going through questions asked before on related issues) over-write C (see above) in the loop, and that because I haven't indexed it. I haven't done so, because I'm not able to.
So I took the largest dimension of the content of B, that is, 266x2 and pre-allocate C before the loop, so
C = zeros(266,2);
and change C=cell2mat(B(r)); to C(r)=cell2mat(B(r));
To no avail, I get 'Unable to perform assignment because the left and right sides have a different number of elements.'
Any thougths?

답변(1개)

Jan
Jan 2021년 7월 24일
Simplify
C=cell2mat(B(r));
to
C = B{r};
This creates a cheap shared data copy, so C does not occupy additional memory: it re-uses the data of B{r}. Therefore a pre-allocation is not useful here.
I do not see a reason to collect the diffent values of C by
C{r} = B{r};
because then C and B contain identical elements.
  댓글 수: 3
Fede C 2018 London
Fede C 2018 London 2021년 7월 26일
Hi Jan,
You're absolutely right, it IS much faster.
C = B{r}; puts into C only the data that is in B{1,2}.
B{1,1} and B{1,2} each contain two matrices, of different row size. Corcoefvector has two rows because I want to store in each the correlation coefficients computed for the data in B{1,1} and B{1,2}.
However, somehow, I only seem to perform this for B{1,2}. However much I fiddle, I can't seem to alter that.
Your simplified (and faster) version also does that, except that now corcoefvector has one row.

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by