I have n
mat-files containing parts of a single huge matrix. I want to load the mat-files and concatenate the row,column,value-vectors to build matrix W
. Right now, I'm doing the following, but it's really slow and I know I shouldn't dynamically increase the size of rows
,cols
,vals
:
rows=[];cols=[];vals=[];
for ii=1:n
var = load( sprintf('w%d.mat', ii) );
[r,c,v] = find( var.w );
rows = [rows; r];
cols = [cols; c];
vals = [vals; v];
end
W = sparse( rows, cols, vals );
Do you know a better way? Thanks in advance!
Solution
Based on Daniel R's suggestion, I solved it like this:
rows=zeros(maxSize,1);
cols=zeros(maxSize,1);
vals=zeros(maxSize,1);
idx = 1;
for ii=1:n
var = load( sprintf('w%d.mat', ii) );
[r,c,v] = find( var.w );
len = size(r,1);
rows(idx:(idx-1+len))=r;
cols(idx:(idx-1+len))=c;
vals(idx:(idx-1+len))=v;
idx = idx+len;
end
W = sparse( rows, cols, vals );
Extremely fast, thanks a lot!