adding one column text file to two column text file using matlab - matlab

I am very much new to MATLAB.
I have two text file. One has two columns xy.txt (X AND Y coordinates). It has 80640 points.
The second has one column z.txt (z value according to the coordinate). The second text file is a result of a matlab program that I wrote. That program produces the z value for every 10 year time interval. I am modelling impact of sea-level rise during this century.
I want to make three column text file to plot contour maps.
I want to include that code to the main script I wrote so that I can get the contour map automatically.
I searched almost a day to find suitable answer but in vain
Thank you

This should give you what you want:
%Open and get the relevant data from the two files
fid1 = fopen('xy.txt');
fid2 = fopen('z.txt');
s1 = textscan(fid1,'%s %s','delimiter','\t');
s2 = textscan(fid2,'%s','delimiter','\t');
%close files
fclose(fid1);
fclose(fid2);
%sort data into an easy to use cell array
s=[s1{1,1},s1{1,2},s2{1,1}];
%Create new file and set permission to write
fid = fopen('xyz.txt','w');
%Loop through cell array s and write to file using a tab delimited format spec.
for ind = 1:size(s,1)
fprintf(fid,'%s\t%s\t%s\n',s{ind,:});
end
fclose(fid); %close file
This assumes that xy.txt and z.txt both have the same number of rows

Related

How to read rows from a text file into an array?

I have a program which finds linear fitting, now I want to provide x elements from text file , y elements will remain the same , I want b(2) as a output for all 128 rows , which will be taken as input from trial2.txt
I want to read 128 rows which contains 3 columns, one by one and put those into x0[], then find b(2)
x0=[];
y0=[5.15659,5.48556,5.80477];
X1 = [ones(length(x0),1) x0'];
b = X1\y0';
plot(x0,y0,'o')
y = b(1) + x0*b(2)
hold on
plot(x0,y,'--r')
fid=fopen('data.txt','a+');
fprintf(fid,'%10.1f %10.4f %10.4f %10.9f\n',x0,b(2));
fclose(fid);
The best way to get started with importing data into MATLAB is to use the interactive "Import Tool". If you like the way it imports your data, you can get it to generate some re-usable MATLAB code so that you don't need to the use the UI next time round.

Efficiency loading a file into Matlab

I am trying to load a file in Matlab. But I am a bit confused about the best way to do it.
The file has 3 columns and looks like the screenshot below:
This file I can load very quickly by doing load('c').
However, I had to add 2 NaNs on the bottom row.
The original file actually looks like the file below:
Now if I do load('c') on the file below I get the error:
Error using load
Unable to read file 'c'. Input must be a MAT-file or an ASCII file containing numeric
data with same number of columns in each row.
Of course I can use ImportData to import this file, but it is just soooo slow to import it.
Any suggestions?
You should be able to use c = readtable('c'). This should automatically change the empty entries to "NaN" by default, but if not, there is a way to set that in the options.
If I have a file that is tricky to import (prior to readtable()...that made things a lot easier in the last few years), I will often use the Import Data tool (if its a really big file you can make a mock-up of the complicated file so it loads faster) then change all the import settings as I would want it, then where the green check says "Import Selection" use the black drop down arrow to select "Generate Function." This will give you the coded way of setting everything up to get the file in just the way you want it.
load() is better suited for reading in previously saved '.mat' files that were created in Matlab.
Here's a low-level approach, which might be faster than other methods:
filename = 'c'; % name of the file
N = 3; % number of columns
fid = fopen(filename, 'r'); % open file for reading
x = fscanf(fid, '%f'); % read all values as a column vector
fclose(fid); % close file
x = [x; NaN(N-mod(numel(x)-1,N)-1, 1)]; % include NaN's to make length a multiple of N
x = reshape(x, N, []).'; % reshape to N columns in row-major order

Getting the format correct when writing data to a text file from a matlab script

I'm trying to write data to a text file from my matlab script. I want two columns which it gives me but I want my time variable (t) followed by my variable (x) which is my amplitude. Its outputting a file like below.
Everything is perfect however i don't believe my (t) variable is first followed by my (x) variable. I'm trying to upload this file to ploy.ly to be graphed but when i set column 1 to my x variable and column 2 to my y variable it plots a oval like below. It's suppose to plot a sinusoidal signal.
My code is as follows:
f = 1E3;
T = 1/f;
tmin = 0;
tmax = 5*T;
dt = T/100;
t = tmin:dt:tmax;
x = sin(2*pi*f*t);
sinData.txt = fopen('sinData.txt','w');
fprintf(sample.txt,'%7.5f,%7.5f\r\n',x);
fclose(sinData.txt);
plot(t,x,'r');
grid on;
MATLAB writes files in column major format. What this means is that it will traverse every row first in one column before moving to the next column. If you have a M x 2 matrix of values where the first column is a vector of t values and the second column is a vector of x values, try transposing the matrix before writing to file. That way, each column represents a pair of (t,x) values for you and MATLAB should be able to preserve writing to the file so that each row is a unique pair.
Also, in your code you are only writing the x values to the file. This makes sense because if you look at your text file going line by line, it pretty much mimics a sinusoidal output. It goes from 0 up to 1, then back to 0 again. Your x vector is a sinusoidal output which thus fits the pattern. As such, you probably want to write the t values as well. To do this, modify the fprintf statement in your code so that it looks like this:
fprintf(sinData.txt,'%7.5f,%7.5f\r\n', [t;x]);
BUG SPOT FROM RTL (Thanks!): Make sure you change sample.txt to sinData.txt in your fprintf statement as that is the name of the handle to the open file that you have opened.
Looking at your code, t and x are row vectors, so this should (hopefully) work. I haven't tried it myself, and I'm somewhere where I don't have MATLAB accessible. Hit me up with a comment and let me know if it works.

Problem concatenating a matrix of numbers with a vector of strings (column labels) using cell2mat

I'm a Mac user (10.6.8) using MATLAB to process calculation results. I output large tables of numbers to .csv files. I then use the .csv files in EXCEL. This all works fine.
The problem is that each column of numbers needs a label (a string header). I can't figure out how to concatenate labels to the table of numbers. I would very much appreciate any advice. Here is some further information that might be useful:
My labels are contained within a cell array:
columnsHeader = cell(1,15)
that I fill in with calculation results; for example:
columnsHeader{1} = propertyStringOne (where propertyStringOne = 'Liq')
The sequence of labels is different for each calculation. My first attempt was to try and concatenate the labels directly:
labelledNumbersTable=cat(1,columnsHeader,numbersTable)
I received an error that concatenated types need to be the same. So I tried converting the labels/strings using cell2mat:
columnsHeader = cell2mat(columnsHeader);
labelledNumbersTable = cat(1,columnsHeader,numbersTable)
But that took ALL the separate labels and made them into one long word... Which leads to:
??? Error using ==> cat
CAT arguments dimensions are not consistent.
Does anyone know of an alternative method that would allow me to keep my original cell array of labels?
You will have to handle writing the column headers and the numeric data to the file in two different ways. Outputting your cell array of strings will have to be done using the FPRINTF function, as described in this documentation for exporting cell arrays to text files. You can then output your numeric data by appending it to the file (which already contains the column headers) using the function DLMWRITE. Here's an example:
fid = fopen('myfile.csv','w'); %# Open the file
fprintf(fid,'%s,',columnsHeader{1:end-1}); %# Write all but the last label
fprintf(fid,'%s\n',columnsHeader{end}); %# Write the last label and a newline
fclose(fid); %# Close the file
dlmwrite('myfile.csv',numbersTable,'-append'); %# Append your numeric data
The solution to the problem is already shown by others. I am sharing a slightly different solution that improves performance especially when trying to export large datasets as CSV files.
Instead of using DLMWRITE to write the numeric data (which internally uses a for-loop over each row of the matrix), you can directly call FPRINTF to write the whole thing at once. You can see a significant improvement if the data has many rows.
Example to illustrate the difference:
%# some random data with column headers
M = rand(100000,5); %# 100K rows, 5 cols
H = strtrim(cellstr( num2str((1:size(M,2))','Col%d') )); %'# headers
%# FPRINTF
tic
fid = fopen('a.csv','w');
fprintf(fid,'%s,',H{1:end-1});
fprintf(fid,'%s\n',H{end});
fprintf(fid, [repmat('%.5g,',1,size(M,2)-1) '%.5g\n'], M'); %'# default prec=5
fclose(fid);
toc
%# DLMWRITE
tic
fid = fopen('b.csv','w');
fprintf(fid,'%s,',H{1:end-1});
fprintf(fid,'%s\n',H{end});
fclose(fid);
dlmwrite('b.csv', M, '-append');
toc
The timings on my machine were as follows:
Elapsed time is 0.786070 seconds. %# FPRINTF
Elapsed time is 6.285136 seconds. %# DLMWRITE

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.