Save double vector in text file

Hello everyone,
I'm trying to save a double array with one row and 5 columns in a text file and then put a new line into the text file. In the next step I change the parameters and the new double array should be saved into the same file so that in the end the result will be a matrix with n rows and 5 columns. Is there a way to do this? The matrix should look like this later:
val1_vec1 val2_vec1 val3_vec1 val4_vec1 val5_vec1
val1_vec2 val2_vec2 val3_vec2 val4_vec2 val5_vec2
val1_vec3 val2_vec3 val3_vec3 val4_vec3 val5_vec3
...
This is my attempt, but it doesn't work out fine, it just keeps writing the new values at the end of the old ones.
Thanks for your help!
fileID = fopen('Mindestgeschwindigkeit.txt','a');
fprintf(fileID, "%d\n\r ", midval);
fprintf(fileID, "\n", midval);
fclose(fileID);

Answers (2)

Change the line that writes the vector to:
fprintf(fileID, "%d ", midval);
That should work, if you want to write each vector as a row vector.
However, the best (and most efficient) option is likely to save the data as a matrix, and then use writematrix to write it all at the same time.
.

8 Comments

This didn't work, the new vector is then saved behind the old one in one row. I wish I could use writematrix, but I change the parameters in my program and every iteration new results come out. So I can't just save the vector results in Matlab, I have to save it in an external text file
Please describe exactly what the code produces (posting it would help), what the problem is, the vector (or vectors) you want to save to the file, and what you want as the result.
I do not understand not being able to save the results. If you are using a for loop, indexing the array is straightforward, and if you are using a while loop, use a counting variable, then reset it, if necessary, with new entries into the loop. Preallocation may not be possible, however even without it, saving the results and writing them to the file at the end would be more efficient than what appears to be the current approach.
If the vectors are different lengths each time, save them to elements of a cell array, then write the cell array to the file using writecell.
.
Hello Star Strider,
the whole code is really long, but here it is:
clear;
factor = [0.25, 0.5, 1.0, 2.0, 4.0];
z_irl_cell = cell(1,5);
irl_cell = readtable("C:\Users\Bruce Rogers\Documents\RoboDK\halfpi\Roboterfahrten\RSI_Auswertung_halfpi\min_vel10_halfpi.txt"); % This is the input, every time the program runs correctly I change the Input text file
z_irl_temp = irl_cell{:,4};
z_irl_cell{:,1} = z_irl_temp;
irl_cell = readtable("C:\Users\Bruce Rogers\Documents\RoboDK\1pi\Roboterfahrten\RSI_Auswertung_1pi\min_vel10_1pi.txt");
z_irl_temp = irl_cell{:,4};
z_irl_cell{:,2} = z_irl_temp;
irl_cell = readtable("C:\Users\Bruce Rogers\Documents\RoboDK\2pi\Roboterfahrten\RSI_Auswertung_2pi\min_vel10_2pi.txt");
z_irl_temp = irl_cell{:,4};
z_irl_cell{:,3} = z_irl_temp;
irl_cell = readtable("C:\Users\Bruce Rogers\Documents\RoboDK\4pi\Roboterfahrten\RSI_Auswertung_4pi\min_vel10_4pi.txt");
z_irl_temp = irl_cell{:,4};
z_irl_cell{:,4} = z_irl_temp;
irl_cell = readtable("C:\Users\Bruce Rogers\Documents\RoboDK\8pi\Roboterfahrten\RSI_Auswertung_8pi\min_vel10_8pi.txt");
z_irl_temp = irl_cell{:,4};
z_irl_cell{:,5} = z_irl_temp;
%%
d_df_mat = zeros(10,5);
for j = 1:length(factor)
z_irl = z_irl_cell{:,j};
num_irl = numel(z_irl);
t = (1:num_irl)*0.004;
A = 50;
b = 10; %Durchgänge
ti = 0.004;
%x = zeros(length(z_irl));
x = 0:ti:(1/factor(j))*10*pi;
x = x';
y = -A*sin(factor(j)*x) + 389.387;
y = y';
%y(j) = y(j)';
num_th = numel(x);
T = (1:length(x))*ti;
% t0_pos1_temp = cell(1,5);
%
% s0_pos1_temp = cell(1,5);
%
% t0_neg1_temp = cell(1,5);
%
% s0_neg1_temp = cell(1,5);
%
% t0_pos2_temp = cell(1,5);
%
% s0_pos2_temp = cell(1,5);
%
% t0_neg2_temp = cell(1,5);
%
% s0_neg2_temp = cell(1,5);
threshold = 389.387; % your value here
[t0_pos1,s0_pos1,t0_neg1,s0_neg1]= crossing_V7(y,T,threshold,'linear'); % positive (pos) and negative (neg) slope crossing points
[t0_pos2,s0_pos2,t0_neg2,s0_neg2]= crossing_V7(z_irl,t,threshold,'linear'); % positive (pos) and negative (neg) slope crossing points
% ind => time index (samples)
% t0 => corresponding time (x) values
% s0 => corresponding function (y) values , obviously they must be equal to "threshold"
% figure(7)
% plot(T,y,'g',t0_pos1,s0_pos1,'+g',t0_neg1,s0_neg1,'+g','linewidth',2,'markersize',12);grid on
% hold on
% plot(t,z_irl,'b',t0_pos2,s0_pos2,'+b',t0_neg2,s0_neg2,'+b','linewidth',2,'markersize',12);grid on
% hold off
% title('Nullstellen beider Wellen, Grün: Theorie, Blau: Realität')
% xlabel('time');
% ylabel('distance');
t0_pos1 = t0_pos1';
s0_pos1 = s0_pos1';
t0_neg1 = t0_neg1';
s0_neg1 = s0_neg1';
t0_pos2 = t0_pos2';
s0_pos2 = s0_pos2';
t0_neg2 = t0_neg2';
s0_neg2 = s0_neg2';
if numel(t0_neg1) ~= 5
t0_neg1_temp2 = 0.004;
t0_neg1_temp3 = [t0_neg1_temp2,t0_neg1'];
t0_neg1_temp3 = t0_neg1_temp3';
t0_neg1 = zeros(length(t0_neg1_temp3),1);
t0_neg1 = t0_neg1_temp3;
end
if numel(t0_neg2) ~= 5
t0_neg2_temp2 = 0.004;
t0_neg2_temp3 = [t0_neg2_temp2,t0_neg2'];
t0_neg2_temp3 = t0_neg2_temp3';
t0_neg2 = zeros(length(t0_neg2_temp3),1);
t0_neg2 = t0_neg2_temp3;
end
if numel(t0_pos1) ~= 5
t0_pos1_temp2 = 0.004;
t0_pos1_temp3 = [t0_pos1_temp2,t0_pos1'];
t0_pos1_temp3 = t0_pos1_temp3';
t0_pos1 = zeros(length(t0_pos1_temp3),1);
t0_pos1 = t0_pos1_temp3;
end
if numel(t0_pos2) ~= 5
t0_pos2_temp2 = 0.004;
t0_pos2_temp3 = [t0_pos2_temp2,t0_pos2'];
t0_pos2_temp3 = t0_pos2_temp3';
t0_pos2 = zeros(length(t0_pos2_temp3),1);
t0_pos2 = t0_pos2_temp3;
end
if numel(s0_neg1) ~= 5
s0_neg1_temp2 = 389.387;
s0_neg1_temp3 = [s0_neg1_temp2,s0_neg1'];
s0_neg1_temp3 = s0_neg1_temp3';
s0_neg1 = zeros(length(s0_neg1_temp3),1);
s0_neg1 = s0_neg1_temp3;
end
if numel(s0_neg2) ~= 5
s0_neg2_temp2 = 389.387;
s0_neg2_temp3 = [s0_neg2_temp2,s0_neg2'];
s0_neg2_temp3 = s0_neg2_temp3';
s0_neg2 = zeros(length(s0_neg2_temp3),1);
s0_neg2 = s0_neg2_temp3;
end
if numel(s0_pos1) ~= 5
s0_pos1_temp2 = 389.387;
s0_pos1_temp3 = [s0_pos1_temp2,s0_pos1'];
s0_pos1_temp3 = s0_pos1_temp3';
s0_pos1 = zeros(length(s0_pos1_temp3),1);
s0_pos1 = s0_pos1_temp3;
end
if numel(s0_pos2) ~= 5
s0_pos2_temp2 = 389.387;
s0_pos2_temp3 = [s0_pos2_temp2,s0_pos2'];
s0_pos2_temp3 = s0_pos2_temp3';
s0_pos2 = zeros(length(s0_pos2_temp3),1);
s0_pos2 = s0_pos2_temp3;
end
% time difference for positive slope crossing points
dt_pos_slope = t0_pos1 - t0_pos2;
% time difference for negative slope crossing points
dt_neg_slope = t0_neg1 - t0_neg2;
d_df = [dt_neg_slope dt_pos_slope]';
d_df = abs(d_df(:));
d_df_temp(:,j) = d_df;
d_df_mat(:,j) = d_df_temp(:,j);
%d_df_mat(:,j) = d_df_temp(:,j);
end
%%
diff_d_df_mat = diff(d_df_mat);
midval = mean(diff_d_df_mat,1);
midval = midval';
fileID = fopen('Mindestgeschwindigkeit.txt','a'); %midval is a 1x5 vector that results of the 5 text files in the input of the program.
fprintf(fileID, "%d\r\n", midval);
fclose(fileID);
% Every time I change the text files (input) a new midval vector will be created
% and I want the result to be saved into a new text file.
% The result should be then created in the next line of the
% 'Mindestgeschwindigkeit.tst' text file
and this is the code for the crossing_V7 function:
function [t0_pos,s0_pos,t0_neg,s0_neg] = crossing_V7(S,t,level,imeth)
% [ind,t0,s0,t0close,s0close] = crossing_V6(S,t,level,imeth,slope_sign) % older format
% CROSSING find the crossings of a given level of a signal
% ind = CROSSING(S) returns an index vector ind, the signal
% S crosses zero at ind or at between ind and ind+1
% [ind,t0] = CROSSING(S,t) additionally returns a time
% vector t0 of the zero crossings of the signal S. The crossing
% times are linearly interpolated between the given times t
% [ind,t0] = CROSSING(S,t,level) returns the crossings of the
% given level instead of the zero crossings
% ind = CROSSING(S,[],level) as above but without time interpolation
% [ind,t0] = CROSSING(S,t,level,par) allows additional parameters
% par = {'none'|'linear'}.
% With interpolation turned off (par = 'none') this function always
% returns the value left of the zero (the data point thats nearest
% to the zero AND smaller than the zero crossing).
%
% [ind,t0,s0] = ... also returns the data vector corresponding to
% the t0 values.
%
% [ind,t0,s0,t0close,s0close] additionally returns the data points
% closest to a zero crossing in the arrays t0close and s0close.
%
% This version has been revised incorporating the good and valuable
% bugfixes given by users on Matlabcentral. Special thanks to
% Howard Fishman, Christian Rothleitner, Jonathan Kellogg, and
% Zach Lewis for their input.
% Steffen Brueckner, 2002-09-25
% Steffen Brueckner, 2007-08-27 revised version
% Copyright (c) Steffen Brueckner, 2002-2007
% brueckner@sbrs.net
% M Noe
% added positive or negative slope condition
% check the number of input arguments
error(nargchk(1,4,nargin));
% check the time vector input for consistency
if nargin < 2 | isempty(t)
% if no time vector is given, use the index vector as time
t = 1:length(S);
elseif length(t) ~= length(S)
% if S and t are not of the same length, throw an error
error('t and S must be of identical length!');
end
% check the level input
if nargin < 3
% set standard value 0, if level is not given
level = 0;
end
% check interpolation method input
if nargin < 4
imeth = 'linear';
end
% make row vectors
t = t(:)';
S = S(:)';
% always search for zeros. So if we want the crossing of
% any other threshold value "level", we subtract it from
% the values and search for zeros.
S = S - level;
% first look for exact zeros
ind0 = find( S == 0 );
% then look for zero crossings between data points
S1 = S(1:end-1) .* S(2:end);
ind1 = find( S1 < 0 );
% bring exact zeros and "in-between" zeros together
ind = sort([ind0 ind1]);
% and pick the associated time values
t0 = t(ind);
s0 = S(ind);
if strcmp(imeth,'linear')
% linear interpolation of crossing
for ii=1:length(t0)
%if abs(S(ind(ii))) > eps(S(ind(ii))) % MATLAB V7 et +
if abs(S(ind(ii))) > eps*abs(S(ind(ii))) % MATLAB V6 et - EPS * ABS(X)
% interpolate only when data point is not already zero
NUM = (t(ind(ii)+1) - t(ind(ii)));
DEN = (S(ind(ii)+1) - S(ind(ii)));
slope = NUM / DEN;
slope_sign(ii) = sign(slope);
t0(ii) = t0(ii) - S(ind(ii)) * slope;
s0(ii) = level;
end
end
end
% extract the positive slope crossing points
ind_pos = find(sign(slope_sign)>0);
t0_pos = t0(ind_pos);
s0_pos = s0(ind_pos);
% extract the negative slope crossing points
ind_neg = find(sign(slope_sign)<0);
t0_neg = t0(ind_neg);
s0_neg = s0(ind_neg);
end
I can’t run that, however that’s not important. I don’t see a loop or anything resembling it (any sort of recursion) anywhere in the code or function, so I can’t determine how it works.
The code change I originally suggested should do what you want. It worked correctly in a test I ran, however I don’t understand the reason that it doesn’t work with your code.
The entire revised part of the code is then:
fileID = fopen('Mindestgeschwindigkeit.txt','a');
fprintf(fileID, "%d ", midval);
fprintf(fileID, "\n", midval);
fclose(fileID);
What does the file actually look like with this change after your code completes?
.
I think you need the text files. These textfiles describe a robot sine wave movement and I'm comparing it to an normal sine wave with different periods. In the end the resulting double array is the mean value of the phase shift of the two sine waves, depending on how fast or slow the robot moved.
The file in the end should look like this:
8pi 4pi 2pi 1pi 0.5pi %header is not neccessary, just for better understanding. 0.5 - 8pi describes period
2.9283 0.0021 0.6572 0.8295 0.8621
5.8922 3.8532 1.8032 0.9855 0.3585
4.8923 4.1231 2.4321 1.9233 0.9884
...
I’m not sure what I need at this point.
What I want is to see what ‘Mindestgeschwindigkeit.txt’ looks like.
Exactly how I showed you above, this is the resulting text file. I don't know sure how it really will look like, because I still haven't solved the problem.
The problem is, why I can't just save it as a total matrix, is that
clear;
would delete every variable and the matrix included. What I do looks like this:
  1. Press run button
  2. Matlab: Loads 5 different sine waves of a robot into Matlab
  3. Program calculates mean phase shift of every robot sine wave and theory sine wave and saves in an 1x5 double vector array
  4. Save this 1x5 double vector array in an text file and generate a new line
  5. After this, the program has finished and I change the file path of the INPUT data.
irl_cell = readtable("C:\Users\Bruce Rogers\Documents\RoboDK\halfpi\Roboterfahrten\RSI_Auswertung_halfpi\min_vel15_halfpi.txt");
from min_vel10.txt to min_vel15.txt for all 5 sine waves.
6. I press run button (as just said, clear; would delete the matrix)
7. Matlab loads 5 new different sine waves
8. Program calculates new mean phase shift
9. Matlab saves this 1x5 double vector array in the same text file that was generated before, BUT this
time, it should be saved in the same text file in the next line
Or for better understanding, here a flowchart attached:
The problem is, that the new line is not created, the result keeps getting stored after the first 1x5 vector, so in total its getting a 1x10, 1x15, 1x20, etc. in the text file.
The text file should have 6 rows (for example) and 5 (fixed value)
I’m lost.
Don’t use clear, especially while the code is executing. It clears everything, making the code much less efficient.
Instead, save the vector and write it at the end.
I’m stopping here.
.

Sign in to comment.

Yongjian Feng
Yongjian Feng on 2 Jul 2021
How about write it as a matrix to a CSV file?
https://www.mathworks.com/matlabcentral/answers/281156-how-can-i-export-a-matrix-as-a-csv-file

5 Comments

It would work, if I can open the CSV file and put in the new results in the next line
Why don't you store the results in an array in your loop, and after that write the entire matrix in one go? That would be much easier.
That was my first suggestion as well.
I have no idea what the problem is.
Hi @Rik,
as you see in Star Striders comment I tried to explain a bit slower what the problem with storing it in a matrix is.
@Bruce Rogers: If you want to insert new rows, read the CSV file back as a matrix first, extend the matix, and save it back into the CSV file.

Sign in to comment.

Categories

Find more on Environment and Settings in Help Center and File Exchange

Products

Release

R2020b

Tags

Asked:

on 2 Jul 2021

Commented:

on 2 Jul 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!