add a table below a text in a file, Matlab fprinf fopen - matlab

I'm using Matlab to develop weather data.
I need to add few lines above the data.
I have a matrix with different data in columns. Let's say:
t=[2;3;6;8;9]; % temperature
v=[10;11;12;10;11]; % wind speed
r=[500;650;750;1000;750]; % solar radiation
table=array2table([t,v,r]);
writetable(table,'file.txt','WriteVariableNames',0);
location='rome';
year=2015;
line1=[location,'_',num2str(year)];
Now I need to add line1 above the numbers.
How can I use fopen and fprintf? With fprintf I just can indicate 'w' and 'a', that is to say overwrite or add below the text.
I thought I could do the contrary: first create a text file with line1 and than use the option 'a' to append the table below.
Unfortunately I can't do it: could you make me an example with my variables?
Thank you

Related

Saving multiple .mat files from workspace to .txt files

I have created a script to create ~300 variable names in my workspace. I need to save these .mat files to .txt files - is there any way to call these variables in some sort of loop or just save them all at once to .txt files?
They are all cells of varying size, about 1000x5 on average.
The first row of the data contains strings, the other elements are all non integer numbers.
Here is an example of one of the .mat files-
http://www.yourfilelink.com/get.php?fid=1065782
I don't know a whole lot about Matlab so any help would be really appreciated! Thank you.
A possible solution could be:
to load the .matfiles through a loop (the name of the file can be either dynamically generated or read from a list)
to extract the first row of the cellarray (the string) and write it in a .txt file by using the dlmwrite function
to remove the first row and write (again with dlmwrite) the numerical values in the .txt having converted them using the cell2mat function.In the writing of the numerical values, the precision has to carefully set.
file_name_root='x2413';
% dummy loop (one iteration) just to test dynamic filename generation
for i=3:3
% generate the name of the input file
input_file_name=[file_name_root int2str(i)];
% generate the name of the output file
output_file_name=[file_name_root int2str(i) '.txt'];
% extract the name of the cellarray and assign it to "the_cell" variable
tmp=load(input_file_name);
var_name=char(fieldnames(tmp));
eval(['the_cell=tmp.' var_name ';'])
[r,c]=size(the_cell);
str='';
% get the first row string (probably a cleaver way to do it exists)
for i=1:c
str=[str ' ' char(the_cell(1,i))];
end
% print the first row in a ".txt" file
dlmwrite(output_file_name,sprintf('%s',str),'delimiter','')
% remove the first row
the_cell(1,:)=[];
% write the numerical values in the ".txt" file
% the "precision" shall be carefully set
dlmwrite(output_file_name,cell2mat(the_cell),'precision','%13.9f','delimiter',' ','-append')
end

load txt dataset into matlab in a matrix structure

I need to read a txt dataset and do some analytics by matlab. the structure of the txt file is like this:
ID Genre AgeScale
1 M 20-26
2 F 18-25
So, I want to load this txt file and build a matrix. I was wondering if someone could help me with this. I used fopen function but it gives me a single array not a matrix with 3 columns.
MATLAB has an interactive data importer. Just type uiimport in the command window. It allows you to:
Name the variable based on heading as shown in your example. You can also manually change them.
Specify variable (column) type, e.g. numeric, cell array of strings, etc.
Auto generate an import script for next use (if desired)
If it works for you then congratulations, you don't need to waste hours to write an data import script :)
Function fopen only returns the file ID and not the content of the file. Once you open the file you use the file ID to read line by line and then parse each line with strsplit using space as the delimiter.
Here's one simple way of doing so:
fid = fopen('textfile.txt');
tline = fgetl(fid);
n = 1;
while ischar(tline)
data(n,:) = strsplit(tline(1:end-1),' ');
n=n+1;
tline = fgetl(fid);
end
fclose(fid);
Keep in mind that the matrix data is type string and not numeric, so if you want to use the numeric values of your dataset, you'll need to take a look at the functions str2num (str2double in newer versions) and strtok to split the AgeScale strings with delimiter '-'.

Is there a compact view for matrices in matlab?

I want to have a look at a large matrix in MATLAB such that all columns are printed in one single line rather than spread out over several lines.
Is such thing possible? That would be great to know.
Try disp(matrixName(:)). The matrixName(:) command turns your matrix into a long vector in column-major order, so it basically just shows you the first column, followed by the second, the third, etc.
If that does not do the trick, you could look into the doprint command.
EDIT: You could also save the matrix to a text file and view the file. You do this like so:
fileID = fopen('C:/path/to/file/myMatrix.txt');
fprintf(fileID, formatString, myMat);
fclose(fileID);
fopen documentation
fprintf documentation
Additional information can be found here
The formatString variable in the above tells fprintf how the data should be displayed. If you have a really big matrix with tons of columns, where all of the values are floats, the easiest way to create this string is to use something like:
formatString = strcat(repmat('%f ', 1, size(myMat, 2)), '\n');
This will create a long string specifying that each element in your matrix is a float, and where it goes, and then cap it off with a line feed so that the next row of your matrix starts on the next line.
Suppress your original matrix with a semicolon and then use the "disp" command to show your matrix however you want.
for i = 1 : length(matrix(1,:))
disp(matrix(:,i))
end
Some "obvious" answers:
You can choose a smaller font - then more values will fit in a line
You can play with the format command to have less digits displayed
(my favourite) Use the variable viewer - via "open selection" or Ctrl-D when the name of a variable is highlighted. This will show your matrix in an excel-like table.

Create a simple table in Matlab

I've been fighting with fprintf for an hour now, should be easy but it's not apparently.
Have a vector with descriptive statistics called datasave, contains 9 numbers like average, standard dev, kurtosis etc.
And I have a vector datalabels with the lablels 'Average' , 'St.dev', 'Kurt' etc.
Open a file with fileopen
print the labels
new line
print the values ( exactly under the labels!)
close the file
This is what I've tried so far:
fileID = fopen('descstat2.txt','w');
fprintf(fileID,'MediaTonnes MinTonnes MaxTonnes Sigma Skew Kurt SigmadTonnes SkewdTonnes KurtdTonnes\r\n');
format short;
fprintf(fileID, '%g\t%g\t%g\n', datasave.');
Help?
I have at least 50 different combinations so I can't really give you my output...
Maybe try this:
fileID = fopen('descstat2.txt','w');
fprintf(fileID,'%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\r\n', datalabels);
fprintf(fileID, '%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g\t%g\r\n', datasave);
fclose
To use XLSWRITE you need to create a cell array:
out = [datalabels(:)'; num2cell(datasave)];
xlswrite('descstat2', out)
If the file you are saving to is exist as a text file, xlswrite will save it as a text as well.
It probably will be slower that fprintf (due to COM interface) but you don't have to deal with formatting the output. Just need to convert everything to cells.
Another option is to use TBLWRITE from Statistical Toolbox. You can just do:
tblwrite(datasave, datalabels, [], filename, '\t')
It will also put row numbers or labels specified as 3rd argument. Might be useful for some data.

MATLAB query about writing results to text file

I have a question about outputting some results to a text file in MATLAB. Essentially I have read in data from 50000 files (numbered sequentially from 1 to 50000) and I have plotted it. Only those files which meet a certain condition are plotted. I now want to add some code which will allow me to write text to a data file. The specific text I want to write is the file numbers (from 1 to 50000) which meet the certain condtions and have been plotted.
When I try and do this the plots work fine but the text file only contains the last file number. For example if the last file number to fulfil the conditions to be plotted is 50000, then the text file only contains 50000. I am unsure how to change the code - any help/advice/tips would be appreciated.
start_sim=1;
end_sim=50000;
h = zeros (1,10000);
for i=start_sim:end_sim
a=int2str(i);
File =strcat('result_', 'simulation', '_', a, 'I_byCal_totale.out');
est_tot=importdata(File, '\t', 1);
cal_tot=est_tot.data;
magnitude=1;
t1=cal_tot(:,1)+1750;
model=cal_tot(:,3)+cal_tot(:,5);
if (model(211)>=25)
if (model(211)<=150)
h(a)=plot(t1,model);
xlim([1910 1970]);
ylim([0 500]);
hold all
clickableLegend(h(a),a,'Location','BestOutside')
%Generate OutputFile
fid = fopen('Modeloutputs.in','w+');
%Generate some text to write in the file (e.g. the simulation number)
% Print the text in the file
fprintf(fid,h(a),'\t','\n');
%close the file
fclose(fid);
end
fid = fopen('Modeloutputs.in','a+');
should do your job. Your initial attempt using 'w+' will
Delete the contents of an existing
file or create new file, and open it
for reading and writing.
as the documentation says. Another option is to move fopen & fclose outside of your loop which I would favor.