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:
- your
P
variable is a struct array, so it has more than 1 element --save()
can save only one file at a time; 2xls
is not a file of your struct, which has aname
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
精彩评论