MATLAB: Append/save same variable with updated values into .mat file(row-wise)

appendmatrow-wisesave

What is the syntax for appending same variable with different values to an existing .mat file? When I use -append, I end up replacing the values!
Example:
for col = 1:10
out = zeros(1,1000000); %reset out to zero vector
x=randn(1,100000);
out=x.^2;
if col == 1
filename='z.mat';
save(filename,'out','-v7.3'); % Write to MAT file
else
save(filename,'out','-v7.3','-append');
end
end
After running the above code, I have the replaced values instead of appending the updated/current values in out into the .mat file after every loop iteration.
Everytime, I iterate through the for loop, I want to save current values in the variable out(1×1000000) into the .mat file row-wise. At the end, I should have (10×1000000) matrix in z.mat and my variable out should hold only 1×1000000 vector during each iteration at a time.
How can I achieve this?
What am I missing?

Best Answer

The proper way to do what you want is to use matfile which lets you read and write to part of variables in a mat file.
filename='z.mat';
m = matfile(filename, 'Writable', true); %Note: writable is true by default IF the file does not exist
for row = 1:10 %why do you call it col when you're asking for rows?
%out = zeros(1,1000000); %completely unnecessary
x = randn(1,1000000);
out = x.^2; %whatever you put into out is overwritten here anyway
m.out(row, 1:1000000) = out;
end
clear m;
Related Question