0
votes

I'm working on a problem where I have an array A of 100 elements. All these 100 elements are changing with time. So in my workspace, I only get the final values of all these elements after the entire time cycle has run.

I'm trying to save the values with time in a separate file (.txt or .mat) so that I can access that file in order to check how the variable varies with time.

I'm trying the following command:

save('file.mat','A','-append');

But this command overwrites the existing values in my file.

Kindly suggest me a way to save these values without overwriting them and also guide me how to access them in MATLAB.

2

2 Answers

2
votes

You can also change the output filename to be unique for each iteration:

for iter=1:n
    A = rand(10);
    save(sprintf('file%d.mat',iter), 'A');
end

That way each iteration creates one file.

0
votes

The reason that saving to a file (even using the -append) flag didn't work is because the variable A already exists in the file and will be over-written each time through the loop. You would need to create a new file or new variable name every time through the loop in order for this to not happen.

Saving the results in a file is probably not the best way to store the time-varying values of A. You would be better off using a cell array to store all intermediate values of A.

A_over_time = cell();

for k = 1:n
    %// Get A somehow
    A_over_time{k} = A;
end

Depending on what A is, you could also store the values of A in a numeric array or matrix.

%// Using an array
A_over_time = zeros(N, 1);
for k = 1:N
    A_over_time(k) = A;
end

%// Using a matrix
A_over_time = zeros(N, numel(A));
for k = 1:N
    A_over_time(k,:) = A;
end