开发者

Saving a file in MATLAB with a variable filename in a loop [duplicate]

This question already has answers here: Closed 11 years ago.

Pos开发者_Python百科sible Duplicates:

Save mat file from MATLAB

How to tell MATLAB to open and save specific files in the same directory

I have a set of CSV files and need to extract data to obtain plots. I use the following code to generate a variable file name in a loop and accordingly get the desired data.

P = dir('*.csv');

for m = 1:length(P)
    P(m).data = csvread(P(m).name);
end

I now want to modify these CSV files (change the data values in the CSV files) before obtaining the desired data and then save these files to Excel format (.xls) within the loop.

Something like

for i = 1:length(P(m).data)
    if P(m).data(i,1)< value1
        P(m).data(i,2) = 0;
    end
    save P(m).xls P(m).data -ascii; % Gives error "save 'P(m).data' is not a valid variable name."
end

How do I save a file in Excel (.xls) format with a variable filename obtaining data from array in a loop?


Check out the MATLAB documentation for the save() function

You need to use the function-call syntax to use variable file names:

save(P(m).xls, P(m).data, '-ascii');

Edit: you seem to have new errors. I can see two things:

  1. your P variable is a struct array, so it has more than 1 element -- save() can save only one file at a time; 2 xls is not a file of your struct, which has a name field.

To save your data, it will probably resemble this:

for m = 1 : length(P),
    save(P(m).name, P(m).data, '-ascii');
end

If you want to replace the extension to avoid overwriting your files (I assume xls is what you wanted), this should do the trick:

for m = 1 : length(P),
    name = P(m).name;
    name = name(1:find(name,'.'));
    name = [name '.xls'];
    save(name, P(m).data, '-ascii');
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜