user3541677
user3541677

Reputation: 21

How to creat a big matrix in MATLAB and fill it gradually in a loop?

I want to create a 36*45 dimensional martrix in MATLAB, but the columns will be filled in a loop. At the beginning I just have a matrix of 36*1 as the initial values to be filled in the first column and gradually by running the loop the rest of columns will be filled. It is important to know that the size of big matrix (36*45) should be known from the beginning.

Upvotes: 1

Views: 516

Answers (2)

Pursuit
Pursuit

Reputation: 12345

Sometimes I fill the matrix in backwards. This prevents the need for a separate allocation line, and sometimes it's quite a bit simpler. (e.g. when filling in an array of structures with indeterminate fields)

That looks like this:

for ix = numColumns:-1:1
    results(:,ix) = <function generating results>;  %No pre-allocation required
end 

Unrelated but interesting side comment below

For some rather bizarre reasons, I think that this is actually somewhat faster than a zeros() call for very large matrices. You can see this by comparing the following:

tic; for ix=1:1000; x = zeros(1000); end; toc
%1.18 second on my current computer

tic; for ix=1:1000; clear('y'); y(1000,1000)=0; end; toc
%0.032 seconds on my current computer

I've seen a good description of the cause of this somewhere on Stackoverflow, but can't find it right now.

Upvotes: 2

Ander Biguri
Ander Biguri

Reputation: 35525

You need to learn a bit about MATLAB basics. I suggest you do that. The code would look like:

A=zeros(36,45);

for ii=1:size(A,2);
   A(:,ii) = %here comes a 36x1 matrix
end

Learn about matrix indexing here: https://uk.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html?refresh=true

Upvotes: 1

Related Questions