Save matlab output in textfile
I have two vectors in matlab with n-entries, let us call them x and y.
Now I want to create a textfile that has the following structure: You have two columns(one for the x values and one for the y-values) and then I want to get:
x(1) y(1) x(2) y(2) x(3) y(3)
and so on.
does anybody here know how this can be done?
You can do this with fprintf in a for loop:
x=[0 1 2 3]; y=[4 5 6 7]; file = 'test.txt'; fh = fopen(file, 'wb'); if( length(x) ~= length(y) ) error('x and y must have the same length'); end for k = 1:length(x) fprintf(fh, '%f %f\n', x(k), y(k)); end fclose(fh);
I assumed that you want to save floating point numbers. To save integer numbers use %d instead of %f.
Here is a way to do it without a loop. I have used a comma delimiter but if you try help dlmwrite you can see that you can easily turn it into a space for example.
x = [1; 2; 3]; y = [4; 5; 6]; dlmwrite('example.txt',[x y],'newline','pc')