I need to load data from file whose file names are enh0.dat, enh1.dat, enh2.dat, …, up to 128 times. So I need to store the file name in a string variable and load data from a file, whose name is stored in the string variable, then store the loaded data in a specified variable for plotting later. But the MATLAB load command loads the data into a variable with a specific name (name of the file containing the data) which does not allow me to automate the use of plot command.
Is it possible to store the name of the file from which I need to load data, in a string variable? I also checked out this
MATLAB newbie: problem reading in file when the file name is stored in a string, but it doesn’t look like it works for me. I get this error when trying to plot the result of textscan:
??? Error using ==> plot Conversion to double from cell is not possible.
This is the code used:
indx = [1:128];
enh_file_cntr = 0;
enh_pre = 'enh';
gain_pre = 'gain';
[enh_file_cntr_str, errmsg1] = sprintf('%d', enh_file_cntr);
enh_file_name = strcat('enh', enh_file_cntr_str, '.dat');
[gain_file_cntr_str, errmsg1] = sprintf('%d', enh_file_cntr);
gain_file_name = strcat('enh', gain_file_cntr_str, '.dat');
fid_enh = fopen(enh_file_name, 'r');
fid_gain = fopen(gain_file_name, 'r');
enh_data = textscan(fid_enh, '%f', 128);
gain_data = textscan(fid_gain, '%f', 128);
subplot(2,3,1);
plot(indx, enh_data, 'b', indx, gain_data, 'r');
If this works I will be incrementing the value of enh_file_cntr in a for loop. How can I fix the above code?
First: The
plotfunction accepts inputs that are of the numerical matrix type. You are trying to input the output of thetextscanfunction which is a cell array. In your case, the first element of the cell array contains a numerical matrix, but the object is not a numerical matrix itself. To retrieve the numerical matrix stored inside the cell, use:prior to calling the plot function. Note: When accessing the elements of a cell array, always use curly braces, ie
{}. When accessing the elements of a numerical matrix, use regular parentheses, ie(). If you have a cell array that contains multiple cells, you can slice it up using().Of course, a cell in a cell array can itself contain a cell array, but maybe don’t worry about this for now 🙂
Second: Make sure to close any file you open with
fopen. ie, once you’ve usedtextscan, then close the file again withfclose(fid_enh).Third, I’m not quite sure I understand what you mean by storing the filename in a string? You appear to be doing exactly that in the code snippet above with the
enh_file_namevariable?