Juliette
Juliette

Reputation: 341

save variables: add new values to a new row in each iteration MATLAB

I have a loop as below

for chnum=1:300
   PI=....
   area=....

   save ('Result.mat' ,'chnum' ,'PI' ,'area',' -append') %-append
    %% I like to have sth like below
    % 1, 1.2,3.7
    % 2, 1,8, 7.8
    % .....

end

but it doesn't save. Do you have any idea why?

Best

Upvotes: 2

Views: 199

Answers (2)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23675

Well, even if it's not part of the question, I don't think that you are using a good approach to save your calculations. Reading/writing operations performed on the disk (saving data on a file is falls in this case) are very expensive in terms of time. This is why I suggest you to proceed as follows:

res = NaN(300,2)

for chnum = 1:300
    PI = ...
    area = ...

    res(chnum,:) = [PI area]; % saving chnum looks a bit like an overkill since you can retrieve it just using size(res,1) when you need it...
end

save('Result.mat','res');

Basically, instead of processing a row and saving it into the file, then processing another row and saving it into the file, etc... you just save your whole data into a matrix and you just save your final result to file.

Upvotes: 2

Georg W.
Georg W.

Reputation: 1356

Analysis of the Problem

The matlab help page for save states that the -append option will append new variables to the saved file. It will not append new rows to the already saved matrices.

Solution

To achieve what you intended you have to store your data in matrices and save the whole matrice with a single call to save().

PI = zeros(300,1);
area = zeros(300,1);
for chnum=1:300
   PI(chnum)=.... ;
   area(chnum)=.... ;
end
save ('Result.mat' ,'chnum' ,'PI' ,'area');

For nicer memory management I have added a pre-allocation of the arrays.

Upvotes: 2

Related Questions