1

I need to save multiple arrays to a text file with the filename the same as the variable name. I have created a vector of all the variables required using the follow lines.

all_var={};
vars=whos;
for(i=1:size(vars,1))
    if(~isempty(regexp(vars(i).name,'A[0-9]','match')))
        all_var{end+1}=vars(i).name;
end
end

I am now struggling to find a way to save all of these variable to file. Any help would be appreciated.

Thank you

1
  • you want to save all arrays to a single text file? Commented Nov 20, 2013 at 19:25

1 Answer 1

2

I'm not sure if I understood correctly. Do you want to save each variable in different files? Assuming you want to save all variables in the same file with, lets say, the first value of the vector as the filename, you could try something like:

filename = sprintf('vector_starting_with%d.mat', vars(1).name);
save(filename)

In case you want separated files for each element in the vector, you could try:

all_var={};
vars=whos;
for(i=1:size(vars,1))
    if(~isempty(regexp(vars(i).name,'A[0-9]','match')))
        all_var{end+1}=vars(i).name;
        varsave=sprintf('vector_%d.mat', vars(i).name)
        save(varsave);
end
end

Sorry that it might have some bugs, right now I don't have MATLAB. Nevertheless, try to go over this documentation.

Edit Let me know if you try this then:

all_var={};
vars=whos;
for(i=1:size(vars,1))
    if(~isempty(regexp(vars(i).name,'A[0-9]','match')))
        all_var{end+1}=vars(i).name;
        filename = sprintf('%d.txt', vars(i).name);
        file = fopen(filename,'w');
        fprintf(file,vars(i).name);
        fclose(file);
end
end
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your reply. However I don't think I have stated my problem very clearly. What I am trying to do is save all variables that begin with "A" to separate text files. The name of the text files needs to be the same as the variable name. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.