Question

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.

Image1

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.

Image2

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;
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top